insert vector to end of vector c++
To insert a vector to the end of another vector in C++, you can use the insert
function along with the end
iterator. Here are the steps to accomplish this:
Create two vectors, let's call them
vector1
andvector2
, with the desired elements.Use the
insert
function onvector1
and pass theend
iterator as the first argument, and thebegin
andend
iterators ofvector2
as the second and third arguments, respectively.
Here is the code snippet that demonstrates these steps:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vector1{1, 2, 3};
std::vector<int> vector2{4, 5, 6};
vector1.insert(vector1.end(), vector2.begin(), vector2.end());
// Print the merged vector
for (auto num : vector1) {
std::cout << num << " ";
}
return 0;
}
In this example, vector1
initially contains the elements 1, 2, 3
, and vector2
contains the elements 4, 5, 6
. After using the insert
function, vector1
will contain the merged elements 1, 2, 3, 4, 5, 6
. The output will be 1 2 3 4 5 6
.