I am appending a vector to another vector using the method (c++):
a.insert(a.end(), b.begin(), b.end());
It works, but if b
is got from a member function, then it won't work anymore, say
vector<point> const line::returnAVectorOfPoints() const
{
vector<point> pts;
// Do something
return pts;
}
Then this time, when I tried to (something like this)
a.insert(a.end(), returnAVectorOfPoints().begin(), returnAVectorOfPoints().end());
I got a segv. Any ideas what's going wrong here?
You are returning a vector by value in line::returnAVectorOfPoints()
, so these two iterators are incompatible:
returnAVectorOfPoints().begin(), returnAVectorOfPoints().end()
They point to two different, temporary, objects.
You could store the return value in a temporary variable:
auto v = returnAVectorOfPoints();
a.insert(a.end(), v.begin(), v.end());
As an aside, note you shouldn't return a const
value. It inhibits move semantics, and this can be quite costly.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments