![](/img/trans.png)
[英]Is it possible to access the real and imaginary parts of a complex number with the [] operator in C++
[英]Getting pointers to the real and imaginary parts of a complex vector in C++
使用標准C ++復數和向量庫,我定義了一個復數向量。 現在,我想獲得包含這個復雜向量的實部和虛部的向量(類型為double *
)。 以下解決方案有效,但由於內存使用量翻倍,因此不夠優雅且浪費;
using namespace std;
typedef complex<double> cmp;
.
.
int i,m=10;
vector<cmp> C(m);
//Do something to populate the vector C
vector<double> R(m), I(m);
for(i=0; i<m; i++){
R[i] = C[i].real();
I[i] = C[i].imag();
}
double * r = &R[0];
double * i = &I[0];
根據C ++標准
If z is an lvalue expression of type cv std::complex<T> then:
— the expression reinterpret_cast<cv T(&)[2]>(z) shall be well-formed,
— reinterpret_cast<cv T(&)[2]>(z)[0] shall designate the real part of z, and
— reinterpret_cast<cv T(&)[2]>(z)[1] shall designate the imaginary part of z.
Moreover, if a is an expression of type cv std::complex<T>* and the expression a[i] is well-defined
for an integer expression i, then:
— reinterpret_cast<cv T*>(a)[2*i] shall designate the real part of a[i], and
— reinterpret_cast<cv T*>(a)[2*i + 1] shall designate the imaginary part of a[i].
所以你可以簡單地寫
using namespace std;
typedef complex<double> cmp;
.
.
int i,m=10;
vector<cmp> C(m);
//Do something to populate the vector C
double * r = &reinterpret_cast<double(&)[2]>( C[0] )[0];
double * i = &reinterpret_cast<double(&)[2]>( C[0] )[1];
這是一個例子
#include <iostream>
#include <complex>
#include <vector>
int main()
{
std::vector<std::complex<double>> v( 1, { 1.1, 2.2 } );
double * r = &reinterpret_cast<double(&)[2]>( v[0] )[0];
double * i = &reinterpret_cast<double(&)[2]>( v[0] )[1];
std::cout << *r << '\t' << *i << std::endl;
return 0;
}
輸出是
1.1 2.2
(C ++ 03)標准沒有定義std::complex<double>
的內部結構,但通常它由2個雙精度組成,真實部分位於虛部之前。 因此,給定std::complex<double>
的數組(或std::vector
),你不能獲得指向所有實部的數組的指針,以及指向所有虛部的數組的另一個指針:實部和虛部是交錯。 如果你真的需要拆分它們,你就不能在不復制所有元素的情況下完成它(就像你已經做的那樣)。
但是你為什么要把它們分開呢? 將它們傳遞給某些庫的某些例程? 也許該庫也支持交錯格式? 在這種情況下,您可以執行reinterpret_cast<double*>(&C[0])
。 請注意,這是非標准的,但在大多數情況下似乎都有效。 有關更多信息,請參閱廣泛使用的fftw庫的文檔 ,建議采用此方法。
如果性能是一個問題,你應該從頭開始分割實部和虛部,而不首先構造一個std::complex<double>
向量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.