使用复向量时出错

Error using complex vector

我需要在 C++ 中访问复杂数据向量的特定元素。

这是我的资料:

vector< complex<float> > x; // Create vector of complex numbers
x.push_back(complex<float>(1, 2)); // Place 1 + j2 in vector
x.push_back(complex<float>(2, 1)); // Place 2 + j1 in vector

// Attempt at accessing the zero-th elements real part
float temp1 = x.at(0).real;
float temp2 = x[0].real;

这会在 Visual Studio 2015 中出现以下错误:

Severity Code Description Project File Line Suppression State Error C3867 'std::_Complex_base::real': non - standard syntax; use '&' to create a pointer to member opencv_dft c : \users\josh\VS_project\main.cpp 101

您忘记了调用 real() 时的括号。您需要:

float temp1 = x.at(0).real();
float temp2 = x[0].real();

real()是成员函数,不是数据成员。

无需在语句 x.push_back(complex(float){1, 2}) 中进行强制转换 - 尽管强制转换无害。也不要忘记对使用 vector 和 complex 的语句使用命名空间 std。

也不要忘记 x.at(0).real 中的 ()s 所以它是 x.at(0).real();.

以下是我使用向量和复数编写程序的方法。

#include <iostream>
#include <complex>
#include <vector>

    using namespace std;

    void main() {
        complex<float> a = { 1,2 };
        a = { 1,4 };
        vector<complex<float>> av;
        av.push_back({ 1,2 });
        cout << av.at(0).real();
    }