I want to overload the operator + in a class which has a vector as member variable, so as to carry out the merging of vectors of two different objects. In other words I would like a new object to be created which has as vector both the elements of the vectors of the two initial vectors in a row. I try the following code and I receive an error in operator+ regarding std::copy. What is the problem?
class TestVector
{
std::vector<int> myVector;
public:
TestVector(){};
TestVector(std::vector<int>);
std::vector<int> getVector();
TestVector operator +(TestVector);
};
std::vector<int> TestVector::getVector()
{
return myVector;
}
TestVector TestVector::operator+(TestVector param)
{
std::vector<int> tempVector;
std::vector<int> paramVector = param.getVector();
std::copy(paramVector.begin(), paramVector.end(), tempVector);
std::copy(myVector.begin(), myVector.end(), tempVector.end());
TestVector TestVector1(tempVector);
return TestVector1;
}
Moreover, is the second copy statement valid to merge two vectors in general?
Update: I got an error at execution time saying that iterators are inompatible at this statement. What is wrong?
tempVector.insert(tempVector.end(),param.getVector().begin(), param.getVector().end());
The third argument to
std::copymust be an iterator, not a container. You can usestd::back_inserterthus:The second copy will compile, since
std::end()returns an iterator, but it will break because the iterator simply points to the end of the vector. It won’t grow the vector whenstd::copytries to assign to it; it will simply invoke undefined behaviour. Again,std::back_insertersolves the problem.In any event you don’t need
std::copyat all, sincestd::vectorprovides the necessary semantics directly:And remember to use
const &…to avoid so much copying. For instance, the second constructor copies the input vector unnecessarily, andgetVector()copies the internal vector unnecessarily.Even the above solution copies the temporary vector at least once, which can be avoided with a purpose-built constructor: