24 Ranges library [ranges]

24.7 Range adaptors [range.adaptors]

24.7.8 Take view [range.take]

24.7.8.1 Overview [range.take.overview]

take_­view produces a view of the first N elements from another view, or all the elements if the adapted view contains fewer than N.
The name views​::​take denotes a range adaptor object ([range.adaptor.object]).
Let E and F be expressions, let T be remove_­cvref_­t<decltype((E))>, and let D be range_­difference_­t<decltype((E))>.
If decltype((F)) does not model convertible_­to<D>, views​::​take(E, F) is ill-formed.
Otherwise, the expression views​::​take(E, F) is expression-equivalent to:
  • If T is a specialization of ranges​::​empty_­view ([range.empty.view]), then ((void) F, decay-copy(E)), except that the evaluations of E and F are indeterminately sequenced.
  • Otherwise, if T models random_­access_­range and sized_­range and is a specialization of span ([views.span]), basic_­string_­view ([string.view]), or ranges​::​subrange ([range.subrange]), then U(ranges​::​begin(E), ranges​::​begin(E) + std​::​min<D>(ranges​::​distance(E), F)), except that E is evaluated only once, where U is a type determined as follows:
    • if T is a specialization of span, then U is span<typename T​::​element_­type>;
    • otherwise, if T is a specialization of basic_­string_­view, then U is T;
    • otherwise, T is a specialization of ranges​::​subrange, and U is ranges​::​subrange<iterator_­t<T>>;
  • otherwise, if T is a specialization of ranges​::​iota_­view ([range.iota.view]) that models random_­access_­range and sized_­range, then ranges​::​iota_­view(*ranges​::​begin(E), *(ranges​::​begin(E) + std​::​
    min<D>(ranges​::​distance(E), F)))
    , except that E is evaluated only once;
  • Otherwise, ranges​::​take_­view(E, F).
[Example 1: vector<int> is{0,1,2,3,4,5,6,7,8,9}; for (int i : is | views::take(5)) cout << i << ' '; // prints: 0 1 2 3 4 — end example]