我有一个包含复数值的 vector (定义为 std::vector<std::complex<double>>
或 arma::cx_vec
),并希望将它们转换为包含两倍大小的双值的 vector 。之后我想再次将它们转换回来。目前我使用两个循环(这里从双 vector 到复 vector 再返回):
//get x and dx as vectors containing real values, with a size of 2 * dim
arma::cx_colvec local_x(dim), local_dx(dim);
for(size_t i = 0; i < x.size(); i += 2) {
local_x(i / 2) = std::complex<double>(x(i), x(i + 1));
}
//Do something with local_x and local_dx
for(size_t i = 0; i < 2 * dim; i += 2) {
dx(i) = local_dx(i / 2).real();
dx(i + 1) = local_dx(i / 2).imag();
}
//Send dx back
我可以想象这可能会相当慢。因此,是否还有其他可能性将这些 vector 从复数 vector reshape 为双倍 vector 并返回?理想情况下涉及迭代器(这样我可以使用诸如 transform()
之类的方法)而不是对某个大小进行循环。
这个问题的背景是:我有复杂的输入数据,必须将其放入函数中 A
我无法修改它,但它再次调用用户提供的函数(称为 U
)。该函数不支持复杂数据类型,仅支持实数类型。因此,我的目的是在将 vector 放入 A
之前将其展平。 ,将其展开 U
,对其进行计算,重新展平并再次发送回来。
最佳答案
std::complex<double>
是 explicitly被称为可被视为 double[2]
的东西
Array-oriented access
For any object
z
of typecomplex<T>
,reinterpret_cast<T(&)[2]>(z)[0]
is the real part ofz
andreinterpret_cast<T(&)[2]>(z)[1]
is the imaginary part ofz
.For any pointer to an element of an array of
complex<T>
namedp
and any valid array indexi
,reinterpret_cast<T*>(p)[2*i]
is the real part of the complex numberp[i]
, andreinterpret_cast<T*>(p)[2*i + 1]
is the imaginary part of the complex numberp[i]
The intent of this requirement is to preserve binary compatibility between the C++ library complex number types and the C language complex number types (and arrays thereof), which have an identical object representation requirement.
所以你可以使用std::vector::data()
获得complex<double> *
,并将其重新解释为 double *
元素数量是原来的两倍。
关于c++ - 将复 vector 展平并将其恢复为双 vector 并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61719509/