Assuming I have 2 standard vectors:
vector<int> a; vector<int> b;
Let's also say the both have around 30 elements.
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!
To insert/append a vector's elements to another vector, we use vector::insert() function.
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.
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.
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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With