C++ Standard Library C++ STL Library

C++ <algorithm> - copy_n() Function



The C++ algorithm::copy_n function is used to copy first n elements from the range starting at first to the range starting at result.

Syntax

template <class InputIterator, class Size, class OutputIterator>
  OutputIterator copy_n (InputIterator first, 
                         Size n, 
                         OutputIterator result);

Parameters

first Specify initial position of the input iterator.
n Specify number of elements to be copied.
result Specify initial position of the output iterator where the result to be stored.

Return Value

Returns an iterator pointing to the element that follows the last element copied to result sequence.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::copy_n function is used to copy first three elements from an array to a vector.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
int main (){
  int arr[] = {10, 20, 30, 40, 50};
  vector<int> vec = {1, 1, 1, 1, 1};
  vector<int>::iterator it;

  //copy first three elements from array to vector
  copy_n(arr, 3, vec.begin());

  cout<<"arr contains:";
  for(int i = 0; i < 5; ++i)
    cout<<" "<<arr[i];

  cout<<"\nvec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

arr contains: 10 20 30 40 50
vec contains: 10 20 30 1 1

❮ C++ <algorithm> Library