C++ std::copy() function explanation with examples

C++ std::copy() function explanation with examples:

copy() function is used to copy items from one iterator to another iterator with a specific range. We can define the start and end position of the source and it will copy all items in this rage to a different destination.

To use copy() function, we need to include <bits/stdc+.h> or header file.

Syntax of std::copy():

The syntax of std::copy() is as below:

Iterator copy(Iterator first, Iterator last, Iterator output)

It copies all the elements pointed by first and last. first element is included in the output but last is not. output is the start position of the final result iterator. It returns one iterator to the end of the destination range where elements have been copied.

Example of std::copy():

Let’s take a look at the below example:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    int inputArr[] = {1,2,3,4,5,6,7,8,9,10};
    vector<int> outputVector(5);

    copy(inputArr + 2, inputArr + 7, outputVector.begin());

    for (int i: outputVector)
        cout<<i<<endl;
}

Output:

It will print the below output:

3
4
5
6
7

It copies all items from inputArr[2] to inputArr[6].

You might also like: