What is the best way to copy one vector to another using conversion while coping? I have following code:
vector<Type2> function1(const vector<Type1>& type1Vector)
{
vector<Type2> type2Vector(type1Vector.size());
for (vector<Type1>::const_iterator it = type1Vector.begin(); it < type1Vector.end(); it++) {
type2Vector.push_back(convertion(*it));
}
return type2Vector;
}
Is there a better way?
Your code actually contains a bug, since type2Vector will be double the size of type1Vector. You actually initialise it to the size of type1Vector and then add the converted elements on top of that.
You can easily use standard algorithms to implement what you want:
#include <algorithm>
#include <iterator>
vector<Type2> function1(const vector<Type1>& type1Vector)
{
vector<Type2> type2Vector;
type2Vector.reserve(type1Vector.size());
std::transform(type1Vector.begin(), type1Vector.end(), std::back_inserter(type2Vector), convertion);
return type2Vector;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With