将复向量展平并还原为双向量并返回

Flatten and restore a complex vector into a double vector and back

我有一个包含复数的向量(定义为 std::vector<std::complex<double>>arma::cx_vec),我想将它们转换为包含两倍大小的双精度值的向量。之后我想再次将它们转换回来。目前我使用两个循环(这里从双向量到复向量再返回):

//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

我可以想象那可能会很慢。因此,是否还有其他可能将这些向量从复数重塑为双精度再返回?理想情况下涉及迭代器(这样我就可以使用 transform() 等方法)而不是对大小进行循环。

这个问题的背景是:我有复杂的输入数据,必须将其放入我无法修改的函数 A 中,但它会再次调用用户提供的函数(称为 U).此函数不支持复杂数据类型,仅支持真实类型。因此,我的意图是在将其放入 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 *,有两倍的元素。