copy_n
Copies a specified number of elements
You're viewing an older version of this page (#4129). View the current version.
Definition
The copy_n() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.
Interface
#include <algorithm>
template < class InputIterator, class Size, class OutputIterator >
OutputIterator copy_n(
InputIterator first,
Size count,
OutputIterator result
);Parameters:
| Parameter | Description |
| first | An input iterator that indicates where to copy elements from |
| count | A signed or unsigned integer type specifying the number of elements to copy |
| result | An output iterator that indicates where to copy elements to |
Description
Copy_n copies elements from the range [first, first + n) to the range [result, result + n).
Return Value
Returns an output iterator where elements have been copied to. It is the same as the returned value of the third parameter, result.
Complexity
The complexity is linear, n assignments are performed.
References
Example 1
Problem
This example of program illustrates the functionality of copy_n() algorithm.
Workings
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
int main()
{
std::string in = "1234567890";
std::string out;
std::copy_n(in.begin(), 4, std::back_inserter(out));
std::cout <<out <<'\n';
return 0;
}Solution
Output:
1234
References