std::ranges::distance - cppreference.com (original) (raw)
Defined in header | ||
---|---|---|
Call signature | ||
template< class I, std::sentinel_for<I> S > requires ( |
(1) | (since C++20) |
template< class I, std::sized_sentinel_for<std::decay_t<I>> S > constexpr std::iter_difference_t<std::decay_t<I>> distance( I&& first, S last ); | (2) | (since C++20) |
template< ranges::range R > constexpr ranges::range_difference_t<R> distance( R&& r ); | (3) | (since C++20) |
1,2) Returns the number of hops from first to last.
- Returns the size of r as a signed integer.
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
- 1 Parameters
- 2 Return value
- 3 Complexity
- 4 Possible implementation
- 5 Example
- 6 Defect reports
- 7 See also
[edit] Parameters
first | - | iterator pointing to the first element |
---|---|---|
last | - | sentinel denoting the end of the range first is an iterator to |
r | - | range to calculate the distance of |
[edit] Return value
The number of increments needed to go from first to last.
last - static_cast<const std::decay_t<I>&>(first).
[edit] Complexity
Linear.
Constant.
[edit] Possible implementation
[edit] Example
#include #include #include #include int main() { std::vector v{3, 1, 4}; assert(std::ranges::distance(v.begin(), v.end()) == 3); assert(std::ranges::distance(v.end(), v.begin()) == -3); assert(std::ranges::distance(v) == 3); std::forward_list l{2, 7, 1}; // auto size = std::ranges::size(l); // error: not a sizable range auto size = std::ranges::distance(l); // OK, but aware O(N) complexity assert(size == 3); }
[edit] Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
LWG 3392 | C++20 | overload (1) takes iterator by value, thus move-onlyiterator lvalue with a sized sentinel was rejected | added overload (2) |
LWG 3664 | C++20 | the resolution of LWG issue 3392 maderanges::distance reject array arguments | accepts them |