To join arrays in C++, you can use the std::copy or std::vector classes.
In this example,
arr1
and arr2
.std::copy
function from the
header to copy elements of arr2
to the end of arr1
.result
containing elements from both arr1
and arr2
.#include <iostream>
#include <algorithm>
int main() {
int arr1[] = {1, 2, 3};
int arr2[] = {4, 5, 6};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
int result[size1 + size2];
std::copy(arr1, arr1 + size1, result);
std::copy(arr2, arr2 + size2, result + size1);
for (int i = 0; i < size1 + size2; i++) {
std::cout << result[i] << " ";
}
return 0;
}
1 2 3 4 5 6
In this example,
std::vector
objects, vec1
and vec2
.insert
method of vec1
to insert elements of vec2
at the end of vec1
.vec1
containing elements from both vec1
and vec2
.#include <iostream>
#include <vector>
int main() {
std::vector<int> vec1 = {1, 2, 3};
std::vector<int> vec2 = {4, 5, 6};
vec1.insert(vec1.end(), vec2.begin(), vec2.end());
for (int num : vec1) {
std::cout << num << " ";
}
return 0;
}
1 2 3 4 5 6
In this tutorial, we learned How to Join Arrays in C++ language with well detailed examples.