A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://en.cppreference.com/w/cpp/algorithm/ranges/../../iterator/ranges/next.html below:

std::ranges::next - cppreference.com

Return the nth successor of iterator i.

The function-like entities described on this page are algorithm function objects (informally known as niebloids), that is:

[edit] Parameters i - an iterator n - number of elements to advance bound - sentinel denoting the end of the range i points to [edit] Return value

1) The successor of iterator i.

2) The nth successor of iterator i.

3) The first iterator equivalent to bound.

4) The nth successor of iterator i, or the first iterator equivalent to bound, whichever is first.

[edit] Complexity

1) Constant.

[edit] Possible implementation
struct next_fn
{
    template<std::input_or_output_iterator I>
    constexpr I operator()(I i) const
    {
        ++i;
        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, S bound) const
    {
        ranges::advance(i, bound);
        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, S bound) const
    {
        ranges::advance(i, n, bound);
        return i;
    }
};
 
inline constexpr auto next = next_fn();
[edit] 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 or its operator++ is lvalue-ref-qualified, ++x.begin() does not compile, while ranges::next(x.begin()) does.

[edit] Example
#include <cassert>
#include <iterator>
 
int main() 
{
    auto v = {3, 1, 4};
    {
        auto n = std::ranges::next(v.begin());
        assert(*n == 1);
    }
    {
        auto n = std::ranges::next(v.begin(), 2);
        assert(*n == 4);
    }
    {
        auto n = std::ranges::next(v.begin(), v.end());
        assert(n == v.end());
    }
    {
        auto n = std::ranges::next(v.begin(), 42, v.end());
        assert(n == v.end());
    }
}
[edit] See also decrement an iterator by a given distance or to a bound
(algorithm function object)[edit] advances an iterator by given distance or to a given bound
(algorithm function object)[edit] increment an iterator
(function template) [edit]

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4