Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why append a vector to another vector is not allowed here?

Tags:

c++

vector

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?

like image 346
Daniel Avatar asked Jan 23 '26 22:01

Daniel


1 Answers

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.

like image 166
juanchopanza Avatar answered Jan 25 '26 11:01

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!