The copy function in C++ Algorithm is employed to duplicate all the elements within the container [first, last] to another container beginning from the position specified as result.
Syntax
template<class InputIterator, class OutputIterator>OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result);
Parameter
It serves as an input iterator pointing to the initial element within the specified range, with the element itself being encompassed within the range.
The final: Serving as an input iterator pointing to the concluding element within the range, excluding the element itself from the range.
It serves as 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 that starts with the result is provided.
Example 1
#include<iostream>
#include<algorithm>
#include<vector>
int main()
{
int newints[]={15,25,35,45,55,65,75};
std::vector<int> newvector(7);
std::copy (newints, 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 progresses from the initial element to the final element.
Data races
Some or all of the container objects are accesed.
Exceptions
The function will raise an exception if any of the container elements also raises an exception.