std::copy_n - cppreference.com

From cppreference.com

Defined in header

<algorithm>

template<classInputIt,classSize,classOutputIt>OutputItcopy_n(InputItfirst,Sizecount,OutputItd_first); (1)(since C++11)
(constexpr since C++20)template<classExecutionPolicy,classForwardIt1,classSize,classForwardIt2>ForwardIt2copy_n(ExecutionPolicy&&policy,ForwardIt1first,Sizecount,ForwardIt2d_first); (2) (since C++17)1) If count is positive, copies all elements in the source range [first, std::next(first,count)) to the destination range [d_first, std::next(d_first,count)). Otherwise does nothing.

The source and destination ranges can overlap, but leads to unpredictable ordering of the results.

2) Same as (1), but executed according to policy.

This overload participates in overload resolution only if the value of the following expression is true:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(until C++20)std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(since C++20)Parameters

first - the beginning of the source range count - number of the elements to copy d_first - the beginning of the destination range policy - the

execution policy

to use Type requirements -InputIt must meet the requirements of

LegacyInputIterator

. -OutputIt must meet the requirements of

LegacyOutputIterator

. -ForwardIt1, ForwardIt2 must meet the requirements of

LegacyForwardIterator

. -Size must be

convertible

to an

integral type

. Return value

The past-the-end iterator of the destination range, or d_first if count is non-positive.

Complexity

Exactly max(count,0) assignments.

Exceptions

2) During the execution process:

If the temporary memory resources required for parallelization are not available,

std::bad_alloc

is thrown.

If an uncaught exception is thrown while accessing objects via an algorithm argument, the behavior is determined by the execution policy (for

standard policies

,

std::terminate

is invoked).

Possible implementation

template<classInputIt,classSize,classOutputIt>constexpr//< since C++20OutputItcopy_n(InputItfirst,Sizecount,OutputItd_first){if(count>0){*d_first=*first;++d_first;for(Sizei=1;i!=count;++i,(void)++d_first)*d_first=*++first;}returnd_first;}Example

Run this code

#include<algorithm>#include<iostream>#include<iterator>#include<numeric>#include<string>#include<vector>intmain(){std::stringin{"1234567890"};std::stringout;std::copy_n(in.begin(),4,std::back_inserter(out));std::cout<<out<<'\n';std::vector<int>v_in(128);std::iota(v_in.begin(),v_in.end(),1);std::vector<int>v_out(v_in.size());std::copy_n(v_in.cbegin(),100,v_out.begin());std::cout<<std::accumulate(v_out.begin(),v_out.end(),0)<<'\n';}Output:

1234 5050 See also