问题描述:

I can index a 2d array with a vector in C as follows:

int main()

{

double mat[5][3] = {{5.5,2.1,1.9},

{6.5,7.0,8.8},

{5.4,3.1,8.9},

{9.0,0.1,2.4},

{5.9,8.0,0.7}};

int in[4] = {3,4,2,1};

double smat[4][3];

int i,j;

for(i=0;i<4;i++)

for(j=0;j<3;j++)

{

{

smat[i][j] = mat[in[i]][j];

}

}

printf("%.1f\n",smat[1][0]); //mat[4][0]=5.9

printf("%.1f\n",smat[0][2]); //mat[3][2]=2.4

printf("%.1f\n",smat[3][1]); //mat[1][1]=7.0

return 0;

}

The code successfully returns:

5.9

2.4

7.0

Question: Can we vectorize the two for-loop operation in C, not using the loops?

网友答案:

Example which use one for-loop operation in C (use function memcpy()):

#include <stdio.h>

double mat[5][3] = {{5.5,2.1,1.9},
                    {6.5,7.0,8.8},
                    {5.4,3.1,8.9},
                    {9.0,0.1,2.4},
                    {5.9,8.0,0.7}};
int in[4] = {3,4,2,1};
double smat[4][3];

void main()
{
    int i;
    for(i = 0; i < 4; i++)
        memcpy(smat[i], mat[in[i]], sizeof(double)*3);

    printf("%.1f\n",smat[1][0]); //mat[4][0]=5.9
    printf("%.1f\n",smat[0][2]); //mat[3][2]=2.4
    printf("%.1f\n",smat[3][1]); //mat[1][1]=7.0
}

(If that's what you mean.)

相关阅读:
Top