Search code examples
c++vectorcomplex-numbers

How to create a vector of complex numbers in c++?


I have two inputs(real and imaginary parts) for n complex numbers. I can't figure out how to store them together in a vector such that i can perform complex calculations with STL complex functions. This is something I tried but Time Limit gets exceeded.

vector<complex<double> > a;
for(i=0;i<d;i++)
{
    int temp;
    cin>>temp;
    real.push_back(temp);
}
for(i=0;i<d;i++)
{
    int temp;
    cin>>temp;
    imag.push_back(temp);
}
for(i=0;i<d;i++)
{
    a.push_back(complex<double>(real[i], imag[i]));
}

Solution

  • Here's an example I used:

    double real;
    double imaginary;
    std::vector<std::complex<double> > database;
    //...
    std::cin >> real;
    std::cin >> imaginary;
    const std::complex<double> temp(real, imaginary);
    database.push_back(temp);
    

    In the above example, I read in the real and imaginary components separately. Next, I create a temporary complex object using the real and imaginary components. Finally, I push_back the value to the database.