Copy Array in C++

C++ copy array

Arrays are used to store different objects of the same data type together at contiguous memory locations. We use arrays extensively in our programs and the array operations come in handy while performing several tasks. In this article, we will discuss how to copy array elements to another array in C++. We will also implement various programs using different ways to copy an array. 

Here, You should remember that you can copy one array to another in C++ only when the source array and the destination array are of the same data type or at least compatible data types. By compatible, we mean those data types which can be converted to other data types. For example, characters in C++ can be stored as integers which make both data types compatible with each other. Before discussing how to copy an array, Let us discuss how arrays are copied in C++.

Shallow Copy And Deep Copy In C++

We have two different ways namely shallow copy and deep copy for copying arrays in C++. Both these ways are fundamentally different in the way they work as we will see in this section. 

In shallow copy, we directly copy the pointer of the destination array to the source array pointer. This makes both the pointers point at the same memory location as described in the figure given below. Here, the actual elements exist in the memory location at only one place. But, we have two array pointers that point at the same location. In this case, If we make changes to elements in any of the arrays, these changes are reflected in another array as well. This is due to the reason that both the arrays are pointing at the same memory location.

Shallow Copy

To perform a shallow copy operation in C++, you can simply point the destination pointer to the source array as shown in the following program.

Output:

  • In the above program, we have created an array ‘arr1’ of size 10. Next, we create a pointer arr2 of the same data type as the array and assign arr1 to arr2. This makes arr2 point at the same location as arr1, which effectively creates a shallow copy of arr1.
  • In the next step we simply print the array elements of arr2 which happen to be exact copies of elements that we pushed to arr1
  • After that, we have changed the element at index 3 in the second array to 100. But, you can observe that the same change has happened in the first array. This confirms that both the arrays are pointing to the same memory location.  

Having understood shallow copy, let us discuss deep copy in C++.

Deep copy is entirely different in the way that it creates the actual copy of array elements at a different location. Each copy of the array is independent of the other and the changes in one array are not reflected in other arrays. Deep copy actually copies array elements to a different location in the memory, therefore, avoiding any conflict of pointers. However, deep copy takes more space as all elements are copied to a different location every time we create a deep copy of the array. 

The following diagram explains the deep copy process. Here, the second array does not point to the same array. Rather, an entirely different array is created in memory with the same elements. 

The code for creating the deep copy of an array in C++ is given below.

Output:

In the above program, we have created an array ‘arr1’ and assigned values from 0 to SIZE-1 to it.  We then create a new array ‘arr2’ of the same size as array ‘arr1’; In the loop, we iteratively assign each element of arr1 to arr2 at the same index. Thus it creates a deep copy of array arr1 in the arr2

When we display the contents of both arrays for the first time, you can see that both arrays are exact replicas of each other. However, when we change the third element of the second array to 100, it is not reflected in the first array. This confirms that arr2 is a deep copy of arr1.

How To Copy Array Elements Using Library Functions in C++?

C++ provides us with different ways to copy the array elements. One of the many ways is to use library functions. C++  provides std::copy(), copy_n(), copy_if(), and copy_backward() functions to copy array elements. These functions are defined in the <algorithm> header file. We will understand the use of each function one by one.

How To Copy Array Elements Using The copy() Function in C++?

The copy() function is used to create a copy of one array element to another array. It takes three input arguments. The prototype of the copy() function is as follows.

  • The function takes three parameters. The ‘first’ defines the iterator to the starting of the container from where the elements are to be copied.
  • The ‘last’ defines the ending of the source iterator i.e the position till which the elements have to be copied.  
  • The ‘result’ defines the iterator to the beginning of the container to which the elements are to be copied.

Let us understand the function through a program to copy array in C++.

The output of the program is given below.

The above program creates a copy of the array elements using the copy() function.

  • We have created an array ‘arr1’ and assigned values from 0 to SIZE-1. We then create a different array ‘arr2’ of the same size as ‘arr1’.
  • We use the copy() function and pass it arguments ‘arr1’, which is the starting iterator, and ‘arr1+SIZE’ that marks the end of arr1 as the last iterator. The ‘arr2’ marks the beginning iterator to which elements have to be copied. 
  • On displaying results from both arrays, we can see both arrays have exact replicas of elements in them. Hence, we have copied the elements from arr1 to arr2 using the copy() function in C++.

How To Copy Array Elements Using The copy_n() Function in C++?

The copy_n() function is another version of ‘copy()’ that allows us to choose how many elements have to be copied in the destination container.  The prototype of the function is given below.

The function takes three parameters which are defined below.

  • The ‘first’ defines the starting iterator of the container from where the elements are to be copied.
  • The ‘n’ defines the number of elements that are to be copied.
  • The ‘result’ defines the iterator to the container to which the elements are to be copied. 

Let us understand the function through a program in C++.

The output of the above program is given below.

  • We have created an array ‘arr1’ and assigned values from 0 to SIZE-1. We then create a different array ‘arr2’ of the size 3 as we want to copy only three elements from arr1 to arr2.
  • We use the copy_n() function and pass it arguments ‘arr1+2’ which is the starting iterator which is at the third element and ‘3’ which marks the number of elements of arr1 to be copied. The ‘arr2’ marks the beginning iterator to which elements have to be copied. On displaying results from both arrays, we can see three elements (2, 3, 4) are copied from arr1 to arr2 starting from 2.

How To Copy Array Elements Using The copy_if() Function in C++?

As the name suggests, the copy_if() function copies the elements of one container to another container based on a condition. We provide a condition through a function as an argument based on which, the elements are copied.  The prototype of the copy_if() function is given below.

The function takes four parameters which are defined below.

  • The ‘first’ defines the starting iterator of the container from where the elements are to be copied.
  • The ‘last’ defines the ending iterator of the container from which the elements are copied. 
  • The ‘result’ defines the iterator to the container to which the elements are to be copied. 
  • The ‘pred’ defines the function which returns a boolean value based on which the elements are copied.

Let us understand the function through a program in C++.

The output of the above program is given below.

  • We have created an array ‘arr1’ and assigned values from 0 to SIZE-1. We then create a different array ‘arr2’ of the size as half of ‘arr1’.
  • We use the copy_if() function and pass it arguments ‘arr1’ which is the starting iterator and ‘arr1+SIZE’ which marks the end of arr1 as the last iterator. The ‘arr2’ marks the beginning iterator to which elements have to be copied.
  • As the fourth parameter, we pass a function that returns true when the element is even. Otherwise, it returns false. So only the even elements are copied to arr2. On displaying results from both arrays, we can see only even elements are copied from arr1 to arr2

How To Copy Array Elements Using The copy_backward() Function in C++?

The copy_backward() function copies the elements from the source container to the destination container in the backward direction. The prototype of the function is given below.

  • The function takes three parameters.
  • The ‘first’ defines the iterator to the starting of the container from where the elements are to be copied. 
  • The ‘last’ defined the ending of the source iterator till where the elements that have to be copied.  
  • The ‘result’ defines the iterator to the end of the container to which the elements are to be copied. It is a backward iterator.

Let us understand the function through a program in C++.

The output of the above program is given below.

  • We have created an array ‘arr1’ and assigned values from 0 to SIZE-1. We then create a different array ‘arr2’ of the same size as the size of ‘arr1’.
  • We use the copy_backward() function and pass it arguments ‘arr1’ which is the starting iterator and ‘arr1+SIZE’ which marks the end of arr1 as the last iterator. The ‘arr2+SIZE’ marks the reverse beginning iterator to which elements have to be copied.
  • On displaying results from both arrays, we can see only even elements are copied from arr1 to arr2

Conclusion

Arrays are widely used in programs to store similar objects together. There are cases where we need to copy our data from one array to another array. In this article,  we have seen multiple ways to copy an array to another array in C++. We have also discussed deep copy and shallow copy and learned how to create deep copy and shallow copy in the programs. We have also seen the C++ library functions to copy the array elements in different ways such as copying the whole array, copying some elements, copying on condition, and backward copy. I hope this article provided you with a thorough insight on how to copy array in C++.

Stay tuned for more informative articles. 

That’s all about how to copy array in C++.

Happy Learning!


import_contacts

You may also like:

Related Posts

  • Split String by comma in C++
    10 November

    Split String by comma in C++

    Table of ContentsUsing the for loopUsing the getline() functionUsing the strtok() functionUsing the std::string::erase() and std::string::find() function In this article, we will split a string by comma in C++. There are several methods available to achieve this. For this, we can create a function and use some inbuilt functions. Using the for loop In this […]

  • C++ wait seconds
    06 November

    How to wait for seconds in C++?

    Table of ContentsWait For Seconds Using The sleep () Function in C++Wait For Seconds Using Thread In C++Wait for seconds using sleep_for() function in C++Wait for seconds using sleep_until() function in C++Wait for seconds using delay() function in C++Wait for seconds using the wait() function in CWait For Seconds Using Timer in C++Conclusion There are […]

  • C++ read file into array
    06 November

    Read file into array in C++

    Table of ContentsHow to declare an array in C++?How To Open A File in C++?C++ Libraries For File HandlingOpening File in C++Open A File in C++ Using The open() FunctionProgram To Read File Into Array In C++Explanation For The CodeTakeaways C++ is a powerful language that provides us with ways to read the data from […]

  • Read CSV file in C++
    01 November

    How to read CSV file in C++?

    Table of ContentsWhat is a CSV File? How To Read A CSV File In C++?C++ Code To Read A CSV FileHow To Read A CSV File Using C-Based Approach?Conclusion CSV files or Comma Separated Value Files are simple yet special files that we use to store data. Here, each value is separated by a comma, and […]

  • Count lines in file in C++
    01 November

    Count lines in file in C++

    Table of ContentsHow To Count Lines In A File In C++?C++ Program To Count Lines In A FileHow To Count Lines In A File In C++ Using C-style Approach?C++ Program to Count Lines In A File using C-style approachConclusion We often store our data into files when we need the data to be persistent and […]

  • Get Number of Elements in Array in C++
    08 October

    Get Number of Elements in Array in C++

    Table of ContentsGet Number of Elements in Array in C++Using the sizeof() functionUsing the pointersUsing the size() functionGet the frequency of each element in array in C++Using nested for loopUsing maps One of the most fundamental collections in any programming language is an array. It stores a similar type of data at specific indices that […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.