The copy_n function in C++ Algorithm specifies the quantity of elements to be duplicated into the fresh container. This function is employed to replicate n elements from the range [first, last) of a container into another container commencing from the result position.
Syntax
template<class InputIterator, class Size, class OutputIterator>
OutputIterator copy_n(InputIterator first, Size n, OutputIterator result);
Parameter
template<class InputIterator, class Size, class OutputIterator>
OutputIterator copy_n(InputIterator first, Size n, OutputIterator result);
At the end: This serves as an input iterator pointing to the final element within the range, excluding the element itself from the range.
The result is an output iterator pointing to the initial element of the fresh container where the elements are duplicated.
Return value
An iterator pointing to the final element of the fresh range starting from the outcome is provided.
Example 1
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
vector<int> u1 = {2,6,8,4,9,4};
vector<int> u2(6);
vector<int> u3(6);
copy(u1.begin(), u1.begin()+3, u2.begin());
cout<<"The new vector with copy contains:";
for(int k=0; k<u2.size(); k++)
cout<<u2[k]<<" ";
copy_n(u1.begin(),4,u3.begin());
cout<<"\n";
cout<<"The new vector using copy_n contains:";
for(int m=0; m<u3.size(); m++)
cout<<u3[m]<<" ";
}
Output:
The new vector with copy contains: 2 6 8 0 0 0
The new vector using copy_n contains:2 6 8 4 0 0
Example 2
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int newints[]={15,25,35,45,55,65,75};
std::vector<int> newvector;
newvector.resize(7);
std::copy_n(newints,7,newvector.begin());
std::cout<<"newvector contains:";
for(std::vector<int>::iterator ti= newvector.begin(); ti!=newvector.end();++ti)
std::cout<<" "<<*ti;
std::cout<<"\n";
return 0;
}
Output:
newvector contains: 15 25 35 45 55 65 75
Complexity
The function's complexity increases linearly as it processes elements from the initial one to the final one.
Data races
Up to n elements of the container are accessed.
Exceptions
The function will raise an exception if any of the container elements also raises an exception.