Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
copy
communitycreator

How to use the copy() function in C++

Harsh Jain

The copy() function in C++ is used to copy the values from an array/vector within a specified range to another array/vector. This function is available in the <algorithm.h> header file.

Parameters

The copy() function accepts the following parameters:

  • first: This is an iterator that points to the first index of the array or vector from where we want to copy the elements.

  • last: This is an iterator that points to the last index of the array or vector to where we want to copy the elements.

  • result: This is an iterator that points to the new array or vector to where we want to store the copied elements. The size of the result should be large enough to accommodate the elements in the range [first, last).

Return

The copy() function returns an iterator that points to the end of the result where last the element has been copied.

Code

Let’s look at the code now to understand it better.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
  int arr[] = {10,20,30,40,50,60,70};
  vector<int> vec (7);

  copy(arr, arr + 7, vec.begin());

  cout << "Copied Vector contains: ";
  for (int x: vec)
    cout << x << " ";

  return 0;
}
Use copy() function in C++

Explanation

  • From lines 1 to 3, we import the required header files.

  • In line 7, we create an array of integers.

  • In line 8, we create the vector where we want to store the copied data from the array.

  • In line 10, we call the copy() function and pass the required parameters. Note that we pass the vec.begin() as the starting address of our result vectorwhere the copied data will be stored.

  • From lines 12 to 14, we print the copied data using a for loop.

RELATED TAGS

c++
copy
communitycreator
RELATED COURSES

View all Courses

Keep Exploring