Home » C++ algorithm copy_n() function

C++ algorithm copy_n() function

by Online Tutorials Library

C++ Algorithm Functions copy_n()

C++ Algorithm copy_n() function specifies the number of elements to be copied into the new container. The function is used to copy n elements of the container [first,last) into a different container starting from result.

Syntax

Parameter

first: It is an input iterator to the first element of the range, where the element itself is included in the range.

last: It is an input iterator to the last element of the range, where the element itself is not included in the range.

result: It is an output iterator to the first element of the new container in which the elements are copied.

Return value

An iterator to the last element of the new range beginning with result is returned.

Example 1

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

Output:

newvector contains: 15 25 35 45 55 65 75  

Complexity

The complexity of the function is linear starting from the first element to the last one.

Data races

Up to n elements of the container are accessed.

Exceptions

The function throws an exception if any of the container elements throws one.

You may also like