gpt4 book ai didi

c - 用 C 中的数组索引二维数组的矢量化

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:04 27 4
gpt4 key购买 nike

我可以在 C 中用一个 vector 索引一个二维数组,如下所示:

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;
}

代码成功返回:

5.9
2.4
7.0

问题:我们可以向量化 C 中的两个 for 循环操作,而不使用循环吗?

最佳答案

在 C 中使用一个 for 循环操作的示例(使用函数 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
}

(如果那是你的意思。)

关于c - 用 C 中的数组索引二维数组的矢量化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27206940/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com