在c++中将结构体数组平整化为多个数组

Flatten array of structs into several arrays in C++

本文关键字:数组 结构体 c++      更新时间:2023-10-16

了解情况的源代码:

struct s { 
    int i; 
    float f 
};
const int cnt = 10;
s *source = new s[cnt];
/*... fill source ...*/
int *dest_i = new int[cnt];
float *dest_f = new float[cnt];
for (int x = 0; x < cnt; x++) {
    dest_i[x] = source[x].i;
    dest_f[x] = source[x].f;
}

所以,这里的问题是:有没有比迭代数组循环更快的方法?

可以展开循环。这是我能想到的全部。

这是一个相当毫无意义的优化自己写,编译器可以尝试为你做,如果你启用它(在gcc中,用--funroll-loops编译)