问题描述
嘿,我有一个 Complex double 数组,我想从另一个基本浮点数组更改它的值,所以基本上我想将所有浮点数组值复制到每个复杂元素的 real
值中。
我尝试在 for 循环中迭代并复制该值,但出现错误,例如 lvalue required as left operand of assignment
这是我的代码:
typedef std::complex<double> Complex;
const Complex test[] = { 0.0,0.114124,0.370557,0.0,-0.576201,-0.370557,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
}
解决方法
您的代码有两个问题:
-
您不能分配给调用
std::complex::real()
的结果 - 它返回一个值,而不是一个引用。您需要改用void real(T value);
重载,请参阅:https://en.cppreference.com/w/cpp/numeric/complex/real。 -
test
被声明为const
,因此在任何情况下都不能分配给它
要解决这些问题,请将您的代码更改为:
typedef std::complex<double> Complex;
Complex test[] = { 0.0,0.114124,0.370557,0.0,-0.576201,-0.370557,0.0 };
for (int i = 0; i < N; i++ )
{
printf ( " %4d %12f\n",i,in[i] );
test[i].real (in[i]);
}