Description:
This C++ article is about the copy_n() algorithm function with std::vector container.
It is an STL algorithm in <algorithm> header file.It
gives the freedom to choose how many
elements have to be copied in destination container
copy_n() has one definition:
template <class InputIterator, class Size, class OutputIterator>
OutputIterator copy_n (InputIterator first, Size n, OutputIterator result);
Return type : An iterator to the end of the destination range where elements have been copied.
Working: The copy_n( ) function takes 3 parameters, two iterators 'first' ,n , result .
first : The pointer to the beginning of source container, from where elements have to be
started copying.
n:Integer specifying how many numbers would be copied to destination container starting
from n.If a negative number is entered, no operation is performed.
result:The pointer to the beginning of destination container, to where elements have to
be started copying.
Implementation:
#include<iostream>
#include<algorithm> // copy_n()
#include<vector>
using namespace std;
int main()
{
// initializing source vector
vector<int> arr = { 1, 2, 4, 3, 9, 6 };
vector<int> arr1(6);
// using copy_n()
copy_n(arr.begin(), 4, arr1.begin());
// printing new vector
cout << "The elements are : ";
for(int i=0; i<arr1.size(); i++)
cout << arr1[i] << " ";
}
Output:
The elements are : 1 2 4 3 0 0
Comments