Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

How to use copy_n() function in C++

Harsh Jain

The copy_n() function in C++ is used to copy the first n values starting from an index to a result vector. This function is available in the <algorithm.h> header file.

Parameters

The copy_n() 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.

  • n: This is the number of elements that we want to copy starting from the first. If the value of n is negative, then the copy_n() function does not perform any operation.

  • 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_n() function returns an iterator that points to the end of the result where the last element has been copied.

Code

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

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

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

  copy_n(arr, n , vec.begin());

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

  return 0;
}
Use copy_n() 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 define the number of elements that we want to copy.

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

  • In line 11, we call the copy_n() function and pass the required parameters. Note that we pass the vec.begin() as the starting address of our result vector.

  • From lines 13 to 15, we print the copied data using a for loop.

This way we can use copy_n() function to copy n elements easily.

RELATED TAGS

c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring