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<list>
int main()
{
std::list<int> lis = {1,2,3,4,5,6,7,8,9,10};
std::list<int> lis_size (lis.size());
// using copy_n()
auto it = copy_n(lis.begin(), 5 , lis_size.begin());
lis_size.resize(std::distance(lis_size.begin(),it));
// printing new list
std::cout << "element contains:";
for (int& x: lis_size) std::cout << ' ' << x;
std::cout << '\n';
}
Output:
element contains: 1 2 3 4 5
Comments