std::ranges::next
From cppreference.com
Defined in header <iterator>
|
||
template< std::input_or_output_iterator I > constexpr I next( I x ); |
(1) | (since C++20) |
template< std::input_or_output_iterator I > constexpr I next( I x, std::iter_difference_t<I> n ); |
(2) | (since C++20) |
template< std::input_or_output_iterator I, std::sentinel_for<I> S > constexpr I next( I x, std::iter_difference_t<I> n, S bound ); |
(3) | (since C++20) |
Return the nth successor of iterator i
.
The function-like entities described on this page are 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.
In practice, they may be implemented as function objects, or with special compiler extensions.
Contents |
Parameters
i | - | an iterator |
n | - | number of elements to advance |
bound | - | sentinel denoting the end of the range i points to
|
Return value
1) The successor of iterator
i
2) The nth successor of iterator
i
3) The nth successor of iterator
i
, or the first iterator equivalent to bound
, whichever is first.Complexity
1) Constant
Possible implementation
struct next_fn { template<std::input_or_output_iterator I> constexpr I operator()(I i) const { return --i; } template< std::input_or_output_iterator I > constexpr I operator()(I i, std::iter_difference_t<I> n) const { ranges::advance(i, n); return i; } template<std::input_or_output_iterator I, std::sentinel_for<I> S> constexpr I operator()(I i, std::iter_difference_t<I> n, I bound) const { ranges::advance(i, n, bound); return i; } }; inline constexpr auto next = next_fn(); |
Notes
Although the expression ++x.begin() often compiles, it is not guaranteed to do so: x.begin() is an rvalue expression, and there is no requirement that specifies that increment of an rvalue is guaranteed to work. In particular, when iterators are implemented as pointers, ++x.begin() does not compile, while ranges::next(x.begin()) does.
Example
Run this code
#include <iomanip> #include <iostream> #include <iterator> #include <vector> int main() { std::vector<int> v{ 3, 1, 4 }; { auto n = std::ranges::next(v.begin()); std::cout << *n << '\n'; } { auto n = std::ranges::next(v.begin(), 2); std::cout << *n << '\n'; } { auto n = std::ranges::next(v.begin(), 42, v.end()); std::cout << std::boolalpha; std::cout << (n == v.end()) << '\n'; std::cout << std::noboolalpha; } }
Output:
1 4 true
See also
(C++20) |
decrement an iterator by a given distance or to a bound (niebloid) |
(C++20) |
advances an iterator by given distance or to a given bound (niebloid) |
(C++11) |
increment an iterator (function template) |