To concatenate two vectors in C++, you can use the `insert` method, `push_back` method, or range constructor.
In this example,
vector1
and vector2
.insert
method on vector1
, passing the iterators of vector2
.insert
method inserts all elements from vector2
into vector1
at the end of vector1
.vector1
to standard output.#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());
for (int num : vector1) {
std::cout << num << " ";
}
return 0;
}
1 2 3 4 5 6
In this example,
vector1
and vector2
.push_back
method on each element of vector2
to append them to vector1
.push_back
method adds each element from vector2
to the end of vector1
.vector1
to standard output.#include <iostream>
#include <vector>
int main() {
std::vector<char> vector1 = {'a', 'b', 'c'};
std::vector<char> vector2 = {'d', 'e', 'f'};
for (char ch : vector2) {
vector1.push_back(ch);
}
for (char ch : vector1) {
std::cout << ch << " ";
}
return 0;
}
a b c d e f
In this tutorial, we learned How to Concatenate Two Vectors in C++ language with well detailed examples.