In C++, you can join vectors by using the `insert()` method or the `insert()` function with iterators.
In this example,
vec1
and vec2
, with different elements.insert()
method to insert all elements of vec2
into vec1
.#include <iostream>
#include <vector>
int main() {
std::vector<int> vec1 = {1, 2, 3};
std::vector<int> vec2 = {4, 5, 6};
// Join vectors using insert() method
vec1.insert(vec1.end(), vec2.begin(), vec2.end());
// Print the combined vector
for (int i : vec1) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
1 2 3 4 5 6
In this example,
vec1
and vec2
, with different elements.insert()
function with iterators to insert all elements of vec2
into vec1
.#include <iostream>
#include <vector>
int main() {
std::vector<int> vec1 = {1, 2, 3};
std::vector<int> vec2 = {4, 5, 6};
// Join vectors using insert() function with iterators
vec1.insert(vec1.end(), vec2.begin(), vec2.end());
// Print the combined vector
for (int i : vec1) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
1 2 3 4 5 6
In this tutorial, we learned How to Join Vectors in C++ language with well detailed examples.