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

Daniel

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?

juanchopanza

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.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Unable to append a vector in a mutex to another vector

From Dev

Best way to append vector to vector

From Dev

Append vector to another with a move (pre C++11)

From Dev

Is inserting an element of a std::vector into the same vector allowed?

From Dev

Julia: append to an empty vector

From Dev

Append a vector to a Matrix

From Dev

Append to a vector (quick method)

From Dev

Python; Append vector to an array

From Dev

Copy vector element of a vector to another vector

From Dev

Why is variable declaration not allowed here?

From Dev

Why is lambda function not allowed here?

From Dev

check if vector contains another vector

From Dev

Assign vector in indexing another vector

From Dev

Count occurence of vector in another vector

From Dev

check if vector contains another vector

From Dev

obtaining a vector from another vector

From Dev

Appending one vector to another vector

From Dev

Clojure: Append vector of strings to string resulting in a vector

From Dev

How to append a vector to a vector r - in a vectorized style

From Dev

Error in assignment of a vector (extract from a vector of vector) to another vector with operator =

From Dev

How to append a vector to a matrix in python

From Java

Append value to empty vector in R?

From Dev

Append values to vector by for loop not working

From Dev

how to append an element to a vector function?

From Dev

boost vector serialization append issue

From Dev

Keras: how to append a vector to a tensor

From Dev

Add a vector at the end of another

From Dev

Assign a vector from another

From Dev

Why do QString and vector<unique_ptr<int>> appear incompatible here?

Related Related

HotTag

Archive