Open In App

copy_n() Function in C++ STL

Last Updated : 27 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Copy_n() is the C++ function defined in <algorithm> library in STL. It helps to copy one array element to the new array. Copy_n function allows the freedom to choose how many elements must be copied in the destination container. This function takes 3 arguments, the source array name, the size of the array, and the target array name.

Function Template:

template <class InputIterator, class Size, class OutputIterator>
OutputIterator copy_n (InputIterator start_limit, Size count, OutputIterator result);

Parameters:

start_limit – Input iterator pointing to the beginning of the range of elements to copy from.
count – Number of elements to copy.
result – Output iterator to the initial position in the new container.

Time Complexity: O(n)
Auxiliary Space: O(n)

Example 1:

C++




// C++ code to demonstrate the
// working of copy_n() function
// Used with array
#include <algorithm>
#include <iostream>
  
using namespace std;
  
int main()
{
    // Initializing the array
    int ar[6] = { 8, 2, 1, 7, 3, 9 };
  
    // Declaring second array
    int ar1[6];
  
    // Using copy_n() to copy contents
    copy_n(ar, 6, ar1);
  
    // Displaying the new array
    cout << "The new array after copying is : ";
    for (int i = 0; i < 6; i++) {
        cout << ar1[i] << " ";
    }
  
    return 0;
}


Output

The new array after copying is : 8 2 1 7 3 9 

Below is the code demonstrating the use of the copy_n() function for vectors.

Example 2:

C++




// C++ code to demonstrate the
// working of copy_n() function
// Used with vector
#include <algorithm>
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
  
    // initializing the source vector
    vector<int> v1 = { 8, 2, 1, 7, 3, 9 };
  
    // declaring destination vectors
    vector<int> v2(6);
  
    // using copy_n() to copy first 3 elements
    copy_n(v1.begin(), 3, v2.begin());
  
    // printing new vector
    cout << "The new vector after copying is : ";
    for (int i = 0; i < v2.size(); i++) {
        cout << v2[i] << " ";
    }
  
    return 0;
}


Output

The new vector after copying is : 8 2 1 0 0 0 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads