how to append one vector to another c++
To append one vector to another in C++, you can use the insert
function provided by the std::vector
container class. Here are the steps to do this:
- Initialize two vectors, let's say
vector1
andvector2
, with the desired elements.
cpp
std::vector<int> vector1 = {1, 2, 3};
std::vector<int> vector2 = {4, 5, 6};
- Use the
insert
function to appendvector2
tovector1
. Theinsert
function takes three arguments: the position where you want to insert the elements, the beginning iterator of the range you want to insert, and the end iterator of the range you want to insert.
cpp
vector1.insert(vector1.end(), vector2.begin(), vector2.end());
In this case, we want to insert vector2
at the end of vector1
, so we use vector1.end()
as the position to insert. We also pass vector2.begin()
as the beginning iterator and vector2.end()
as the end iterator to indicate the range of elements to be inserted.
- After the insertion,
vector1
will now contain the elements from bothvector1
andvector2
.
cpp
// Output: 1 2 3 4 5 6
for (int num : vector1) {
std::cout << num << " ";
}
The output will show all the elements in vector1
, including the elements appended from vector2
.
Note: This method uses the insert
function to append one vector to another. Another approach is to use the push_back
function to insert each element from vector2
into vector1
individually. However, using insert
with iterators is more efficient when appending a large number of elements.