gpt4 book ai didi

c++ - 如何从结构数组中提取数组?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:44:33 24 4
gpt4 key购买 nike

在 C++ 中,为了使用复数,我将结构类型“creal”定义为

  typedef struct {  
double re;
double im; } creal;

现在令“length”为初始化为的结构数组“complex_vector”的元素数

creal complex_vector[length];

然后填充数据。

我想从“complex_vector”中提取两个数组“real_vector”和“imag_vector”。到目前为止,我一直使用 for 循环:

double real_vector[length];
double imag_vector[length];
for (int n = 0; n < length; n++)
{
real_vector[n] = complex_vector[n].re;
imag_vector[n] = complex_vector[n].im;
}

我想知道是否有办法避免 for 循环并直接提取结构数组“complex_vector”的值以创建数组“real_vector”和“imag_vector”。

感谢您的帮助。

最佳答案

无法避免循环,因为 complex_vector 中的数据是交错的

re0 im0 re1 im1 re2 im2 ... reN imN

并且您的目标代表是非交错的

re0 re1 re2 ... reN
im0 im1 im2 ... imN

因此必须以任何方式进行复制。您如何使用一些 for_each 魔法以更紧凑的形式编写代码,但在我看来,这只会使代码更难以理解。

编辑:
然后使用一些更复杂的矩阵类(例如在 OpenCV cv::Mat_ 中)可以通过使用相同的数据缓冲区但修改步长来避免这种复制。但这当然是以元素访问速度变慢为代价的。

关于c++ - 如何从结构数组中提取数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23513917/

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