How to Copy One Array to Another in C++?
In C++, arrays are a type of data structure that stores a fixed-size collection of elements of the same type in a contiguous memory location, and sometimes we need to copy the contents of one array to another. In this article, we will learn how to copy one array to another in C++.
Example:
Input: arr1 = {10, 20, 30, 40, 50, 60} Output: arr2: {10, 20, 30, 40, 50, 60}
Copy All Elements of One Array to Another Array
For copying all the elements stored in one array to another in C++, we can use the std::copy()
function provided in the STL <algorithm>
library that copies a range of elements from one container to another.
Syntax to Use std::copy
copy(strt_iter1, end_iter1, strt_iter2)
Here,
- strt_iter1 is the iterator to the beginning of the first array.
- end_iter1 is the iterator to the end of the first array.
- strt_iter2 is the iterator to the beginning of the second array where we have to copy the elements of the first array.
C++ Program to Copy One Array to Another
The below program demonstrates how we can copy one array to another using copy()
function in C++.
// C++ program to illustrate how to copy one array to
// another
#include <algorithm>
#include <iostream>
using namespace std;
// Driver code
int main()
{
// First array
int arr1[] = { 10, 20, 30, 40, 50, 60 };
int n = sizeof(arr1) / sizeof(arr1[0]);
// Print the first array
cout << "Array 1: ";
for (int i = 0; i < n; i++)
cout << arr1[i] << " ";
cout << endl;
// Second array to store the elements of the first array
int arr2[n];
// Copy first array to second array
copy(arr1, arr1 + n, arr2);
// Print the second array
cout << "Array 2: ";
for (int i = 0; i < n; i++)
cout << arr2[i] << " ";
cout << endl;
return 0;
}
Output
Array 1: 10 20 30 40 50 60 Array 2: 10 20 30 40 50 60
Time Complexity: O(n), where n is the number of elements being copied.
Auxiliary Space: O(n)