Reputation: 6488
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
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
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
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