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

+3


source to share


2 answers


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)};

      

+6


source


You are initializing the array incorrectly. Try the following:



std::complex<double> Uf[2]={{1, 2},{3, 4}};

      

+2


source







All Articles