chintan s
chintan s

Reputation: 6488

convert two vector<double> to form vector<complex<double>>

I have two vectors of type double and I want to combine them to make a complex vector.

vector<double> vReal;
vector<double> vImag;

How do I combine the above two to get

vector<complex<double>> vComp;

Can somebody please help me how do I do it?

Many Thanks.

Best Regards

Chintan

Upvotes: 0

Views: 2171

Answers (4)

stardust
stardust

Reputation: 5988

If no support for C++11

std::complex<double> make_complex(double re, double im) {
    return std::complex<double>(re,im);
}

std::transform(vReal.begin(), vReal.end(), vImag.begin(), std::back_inserter(vComp), make_complex);

Upvotes: 1

hansmaad
hansmaad

Reputation: 18905

    vComp.reserve(vReal.size());

    std::transform(
        begin(vReal), end(vReal), begin(vImag), 
        std::back_inserter(vComp), 
        [](double r, double i) { return std::complex<double>(r, i); });

Upvotes: 5

Oswald
Oswald

Reputation: 31647

Use std::transform, supplying a suitable BinaryOperation.

Upvotes: 2

Salgar
Salgar

Reputation: 7775

for(int i = 0; i < vReal.size(); ++i) {
  complex<double> iNum(vReal[i], vImag[i]);
  vComp.push_back(iNum);
}

Or am I missing something?

Perhaps also a check to make sure vReal and vImag are the same size otherwise you'll crash.

Upvotes: 1

Related Questions