Best way to copy C ++ vector to another with conversion

What is the best way to copy one vector to another using conversion while copying? I have the 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?

+4
source share
1 answer

There is an error in your code, as it type2Vectorwill be half as much type1Vector. You actually initialize it by size type1Vector, and then add the transformed elements on top of it.

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;
}
+12
source

Source: https://habr.com/ru/post/1613805/


All Articles