c++ - 将复 vector 展平并将其恢复为双 vector 并返回

标签 c++ vector complex-numbers

我有一个包含复数值的 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 type complex<T>, reinterpret_cast<T(&)[2]>(z)[0] is the real part of z and reinterpret_cast<T(&)[2]>(z)[1] is the imaginary part of z.

For any pointer to an element of an array of complex<T> named p and any valid array index i, reinterpret_cast<T*>(p)[2*i] is the real part of the complex number p[i], and reinterpret_cast<T*>(p)[2*i + 1] is the imaginary part of the complex number p[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/

相关文章:

python - Tensorflow - 从 Complex64 转换为 2x float32

c++ - vector 乘法中的 SIMD 与 OMP

c++ - 为什么我不能创建大小为 n 的数组?

.net - 根据角度计算从矩形中的点到边缘的向量

Python nan 与复杂数组

matlab - 在 MATLAB 中数值计算复值函数的导数

c++ - 在 C++ 中重新定义与覆盖

c++ - 与linux和windows c++兼容的共享内存库

c++ - std::vector<int, std::allocator<char>> 有效吗?

c++ - 如何通过复制和引用将 vector 传递给函数?