std::ranges::copy_n, std::ranges::copy_n_result
std::ranges
<algorithm>
requires std::indirectly_copyable <I, O>
constexpr copy_n_result<I, O>
using copy_n_result = ranges::in_out_result <I, O>;
[
0,
n)
. The behavior is undefined if result is within the range [
first,
first + n)
(ranges::copy_backward might be used instead in this case).The function-like entities described on this page are algorithm function objects (informally known as niebloids), that is:
- Explicit template argument lists cannot be specified when calling any of them.
- None of them are visible to argument-dependent lookup.
- When any of them are found by normal unqualified lookup as the name to the left of the function-call operator, argument-dependent lookup is inhibited.
Contents
[edit] Parameters
[edit] Return value
ranges::copy_n_result{first + n, result + n} or more formally, a value of type ranges::in_out_result that contains an input_iterator
iterator equals to ranges::next (first, n) and a weakly_incrementable
iterator equals to ranges::next (result, n).
[edit] Complexity
Exactly n assignments.
[edit] Notes
In practice, implementations of std::ranges::copy_n
may avoid multiple assignments and use bulk copy functions such as std::memmove if the value type is TriviallyCopyable and the iterator types satisfy contiguous_iterator
. Alternatively, such copy acceleration can be injected during an optimization phase of a compiler.
When copying overlapping ranges, std::ranges::copy_n
is appropriate when copying to the left (beginning of the destination range is outside the source range) while std::ranges::copy_backward is appropriate when copying to the right (end of the destination range is outside the source range).
[edit] Possible implementation
struct copy_n_fn { template<std::input_iterator I, std::weakly_incrementable O> requires std::indirectly_copyable <I, O> constexpr ranges::copy_n_result<I, O> operator()(I first, std::iter_difference_t <I> n, O result) const { for (; n-- > 0; (void)++first, (void)++result) *result = *first; return {std::move(first), std::move(result)}; } }; inline constexpr copy_n_fn copy_n{};
[edit] Example
#include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <string> #include <string_view> int main() { const std::string_view in{"ABCDEFGH"}; std::string out; std::ranges::copy_n(in.begin(), 4, std::back_inserter (out)); std::cout << std::quoted (out) << '\n'; out = "abcdefgh"; const auto res{std::ranges::copy_n(in.begin(), 5, out.begin())}; const auto i{std::distance (std::begin (in), res.in)}; const auto j{std::distance (std::begin (out), res.out)}; std::cout << "in[" << i << "] = '" << in[i] << "'\n" << "out[" << j << "] = '" << out[j] << "'\n"; }
Output:
"ABCD" in[5] = 'F' out[5] = 'f'
[edit] See also
(algorithm function object)[edit]
(algorithm function object)[edit]
(algorithm function object)[edit]
(algorithm function object)[edit]