Initializing an array of complex numbers in C ++
I need to create an array consisting of complex numbers. I used the following code to initialize it.
std::complex<double> Uf[2]={(1, 2),(3, 4)};
I expect Uf [0] to be 1 + 2*i
both Uf[1]
equal 3+ 4*i
, but when I debug the program I find that imaginary values ββare shown as real and surprisingly imaginary values ββare zero for both numbers (ie Uf[0]
real: 2.0000..
imag: 0.0000
.... and Uf[1]
real: 4.0000
.. imag: 0.0000
.. Can someone explain to me how to figure this out?
thank
source to share
This is because you are using the comma operator, so complex values ββwill be initialized with 2
and 4
accordingly. Instead, replace the parentheses with curly braces:
std::complex<double> Uf[2]={{1, 2},{3, 4}};
If the above doesn't work, your compiler is not C ++ 11 compatible and you must explicitly create the array elements:
std::complex<double> Uf[2]={std::complex<double>(1, 2),std::complex<double>(3, 4)};
source to share