Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ extend a vector with another vector

Tags:

c++

vector

I'm a C/Python programmer in C++ land working with the STL for the first time.

In Python, extending a list with another list uses the .extend method:

>>> v = [1, 2, 3] >>> v_prime = [4, 5, 6] >>> v.extend(v_prime) >>> print(v) [1, 2, 3, 4, 5, 6] 

I currently use this algorithmic approach to extend vectors in C++:

v.resize(v.size() + v_prime.size()); copy(v_prime.begin(), v_prime.end(), v.rbegin()); 

Is this the canonical way of extending vectors, or if there is a simpler way that I'm missing?

like image 227
cdleary Avatar asked Nov 24 '08 04:11

cdleary


People also ask

How do you append to a vector?

Appending to a vector means adding one or more elements at the back of the vector. The C++ vector has member functions. The member functions that can be used for appending are: push_back(), insert() and emplace(). The official function to be used to append is push_back().

Can you put a vector in a vector C++?

Yes! Yes, you can make a vector of vectors in C++. The normal vector is a one-dimensional list data structure. A vector of vectors is a two-dimensional list data structure, from two normal vectors.

How do you expand a vector in C++?

In C++ the length of a vector or any C++ container, is called the size. The vector can be expanded with the following member functions: resize(), insert(), emplace() and push_back(). Other related member functions are: size(), capacity(), and reserve().


1 Answers

From here

// reserve() is optional - just to improve performance v.reserve(v.size() + distance(v_prime.begin(),v_prime.end())); v.insert(v.end(),v_prime.begin(),v_prime.end()); 
like image 89
Dmitry Khalatov Avatar answered Oct 11 '22 21:10

Dmitry Khalatov