Why is adding a vector to another vector prohibited here?

I add a vector to another vector using a method (C ++):

a.insert(a.end(), b.begin(), b.end());

It works, but if bobtained from a member function, then it will no longer work, say

vector<point> const line::returnAVectorOfPoints() const
{
    vector<point> pts;
    // Do something
    return pts;
}

Then this time when I tried (something like this)

a.insert(a.end(), returnAVectorOfPoints().begin(), returnAVectorOfPoints().end());

I have segv. Any ideas what is going wrong here?

+3
source share
5 answers

You return a vector by value in line::returnAVectorOfPoints(), so these two iterators are incompatible:

returnAVectorOfPoints().begin(), returnAVectorOfPoints().end()

They point to two different time objects.

You can save the return value in a temporary variable:

auto v = returnAVectorOfPoints();
a.insert(a.end(), v.begin(), v.end());

You should not return a value as a note const. It prohibits the semantics of movement, and it can be quite expensive.

+7

, :

line::returnAVectorOfPoints() 

, , :

vector<point> vec = returnAVectorOfPoints();
a.insert(a.end(), vec.begin(), vec.end());
+2

, , .

auto pts = returnAVectorOfPoints();
a.insert(a.end(), pts.begin(), pts.end());
+2

, .

vector<point>& const line::returnAVectorOfPoints() const
+1

pts . pts .

- :

vector<point> &line::returnAVectorOfPoints(vector<point> &pts) const
{    
    // Do something
    return pts;
}

vector<point> a;
returnAVectorOfPoints(a);

, , .

I believe that the reason it will not work, as you wrote, is because the vector does not have a copy constructor that would allow the compiler to create an intermediate copy of the glasses before it goes out of scope. Even if the vector had a copy constructor creating this intermediate copy, it would be an expensive computational process.

Passing a class by reference avoids unnecessary copies.

+1
source

All Articles