To copy an array in C++, you can use the copy() algorithm from the
In this example,
arr1
with elements.arr2
with the same length as arr1
.copy()
algorithm from the
header to copy elements from arr1
to arr2
.#include <iostream>
#include <algorithm>
#include <iterator>
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[sizeof(arr1) / sizeof(arr1[0])];
std::copy(std::begin(arr1), std::end(arr1), std::begin(arr2));
std::cout << "Array 1:";
for (int i : arr1) {
std::cout << " " << i;
}
std::cout << "\nArray 2 (copy of Array 1):";
for (int i : arr2) {
std::cout << " " << i;
}
return 0;
}
Array 1: 1 2 3 4 5 Array 2 (copy of Array 1): 1 2 3 4 5
In this tutorial, we learned How to Copy an Array in C++ language with well detailed examples.