Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a vector to a vector [duplicate]

Tags:

c++

stl

vector

Assuming I have 2 standard vectors:

vector<int> a; vector<int> b; 

Let's also say the both have around 30 elements.

  • How do I add the vector b to the end of vector a?

The dirty way would be iterating through b and adding each element via vector<int>::push_back(), though I wouldn't like to do that!

like image 900
sub Avatar asked Mar 31 '10 09:03

sub


People also ask

How do you append a vector to another vector?

To insert/append a vector's elements to another vector, we use vector::insert() function.

Can you put a vector in a vector?

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 I push a vector to another vector in C++?

Begin Initialize a vector v1 with its elements. Declare another vector v2. Make a for loop to copy elements of first vector into second vector by Iterative method using push_back(). Print the elements of v1.


2 Answers

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

or

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

The second variant is a more generically applicable solution, as b could also be an array. However, it requires C++11. If you want to work with user-defined types, use ADL:

using std::begin, std::end; a.insert(end(a), begin(b), end(b)); 
like image 154
Andreas Brinck Avatar answered Sep 24 '22 01:09

Andreas Brinck


std::copy (b.begin(), b.end(), std::back_inserter(a)); 

This can be used in case the items in vector a have no assignment operator (e.g. const member).

In all other cases this solution is ineffiecent compared to the above insert solution.

like image 26
4 revs, 2 users 50%user184968 Avatar answered Sep 22 '22 01:09

4 revs, 2 users 50%user184968