Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 481
McHay Avatar asked Dec 15 '22 10:12

McHay


1 Answers

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;
}
like image 158
Angew is no longer proud of SO Avatar answered Dec 24 '22 10:12

Angew is no longer proud of SO