yarin Cohen
yarin Cohen

Reputation: 1142

How to change the real value of Complex array elements in c++

Hey I have a Complex double array and I want to change the values of it from another basic float array, so basically I want to copy all the float array values into the real value of each complex element.

I tried to iterate in a for loop and copy the value but I get errors such lvalue required as left operand of assignment

Here is my code:

typedef std::complex<double> Complex;

const Complex test[] = { 0.0, 0.114124, 0.370557, 0.0, -0.576201, -0.370557, 0.0, 0.0 }; // init the arr with random numbers

for ( i = 0; i < N; i++ )
{
    printf ( "  %4d  %12f\n", i, in[i] );
    test[i].real() = in[i]; // this line returns an error
}

can someone please let me know what the correct way of doing so as I'm new to this subject.

Upvotes: 1

Views: 2105

Answers (1)

catnip
catnip

Reputation: 25388

There are two issues with your code:

  1. You cannot assign to the result of calling std::complex::real() - it returns a value, not a reference. You need to use the void real(T value); overload instead, see: https://en.cppreference.com/w/cpp/numeric/complex/real.

  2. test is declared const so you cannot assign to it in any case

To fix these issues, change your code to this:

typedef std::complex<double> Complex;

Complex test[] = { 0.0, 0.114124, 0.370557, 0.0, -0.576201, -0.370557, 0.0, 0.0 };

for (int i = 0; i < N; i++ )
{
    printf ( "  %4d  %12f\n", i, in[i] );
    test[i].real (in[i]);
}

Upvotes: 1

Related Questions