To append a vector to another vector in C++, you can use the `insert` method, `push_back` method, or range constructor.
In this example,
vector1
and vector2
with different values.insert
method on vector1
, passing the iterator pointing to the end of vector1
and the iterators of vector2
.insert
method inserts all elements from vector2
into vector1
at the position indicated by the iterator.vector1
to standard output.#include <iostream>
#include <vector>
int main() {
std::vector<int> vector1 = {1, 2, 3, 4};
std::vector<int> vector2 = {5, 6, 7};
vector1.insert(vector1.end(), vector2.begin(), vector2.end());
for (int num : vector1) {
std::cout << num << " ";
}
return 0;
}
1 2 3 4 5 6 7
In this example,
vector1
and vector2
with different values.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<int> vector1 = {1, 2, 3, 4};
std::vector<int> vector2 = {5, 6, 7};
for (int num : vector2) {
vector1.push_back(num);
}
for (int num : vector1) {
std::cout << num << " ";
}
return 0;
}
1 2 3 4 5 6 7
In this example,
vector1
and vector2
with different values.vector2
to vector1
constructor.vector2
to vector1
.vector1
to standard output.#include <iostream>
#include <vector>
int main() {
std::vector<int> vector1 = {1, 2, 3, 4};
std::vector<int> vector2 = {5, 6, 7};
vector1.insert(vector1.end(), vector2.begin(), vector2.end());
for (int num : vector1) {
std::cout << num << " ";
}
return 0;
}
1 2 3 4 5 6 7
In this tutorial, we learned How to Append a Vector to another Vector in C++ language with well detailed examples.