std::copy() function in C++ STL

The std::copy is a library function of algorithm header of C++ Standard Library which is used to copy the elements of a container. This function copies all the elements of a container for the given range to another container.

Syntax:

std::copy(Iterator startingAddress, Iterator endingAddress, Iterator targetStart);

Parameter: The std::copy() function accepts the following parameters that are given below:

  1. startingAddress: This parameter is the address of the starting element of the source container.
  2. endingAddress: This parameter is the address of the ending element of the source container.
  3. targetStart: This parameter is the address of the starting element of the target container.

Example of std::copy() Function

Program

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

void print_array(int data[], int n) 
{ 
    for(int i = 0; i < n; ++i) 
        cout << data[i] << " "; 
} 

int main()
{
    int Source[] = { 1, 2, 3, 4, 5};
    
    int Target[5];
    
    copy(Source, Source + 5, Target);
    
    cout << "Source: ";
    print_array(Source, 5);
    cout << endl;

    cout << "Target: ";
    print_array(Target, 5);

    return 0;
}

Output

Source: 1 2 3 4 5 
Target: 1 2 3 4 5 

This article is written by

Pratik Singhal

Pratik Singhal

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

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

Scroll to Top