Namespaces
Variants

std::ranges::advance

From cppreference.com
 
 
Iterator library
Iterator concepts
Iterator primitives
Algorithm concepts and utilities
Indirect callable concepts
Common algorithm requirements
(C++20)
(C++20)
(C++20)
Utilities
(C++20)
Iterator adaptors
Range access
(C++11)(C++14)
(C++14)(C++14)  
(C++11)(C++14)
(C++14)(C++14)  
(C++17)(C++20)
(C++17)
(C++17)
 
Defined in header <iterator>
Call signature
template< std::input_or_output_iterator I >
constexpr void advance( I& iter, std::iter_difference_t<I> count );
(1) (since C++20)
template< std::input_or_output_iterator I, std::sentinel_for<I> S >
constexpr void advance( I& iter, S bound );
(2) (since C++20)
template< std::input_or_output_iterator I, std::sentinel_for<I> S >
constexpr std::iter_difference_t<I>
    advance( I& iter, std::iter_difference_t<I> count, S bound );
(3) (since C++20)

Increments (or decrements) the given iterator iter.

1) If count is non-negative, iter is incremented by count steps.
If count is negative, iter is decremented by -count steps. If I does not model bidirectional_iterator, the behavior is undefined in this case.
2) iter is modified so that iter == bound.
  • If I and S model std::assignable_from<I&, S>, equivalent to iter = std::move(bound).
  • Otherwise, if S and I model std::sized_sentinel_for<S, I>, equivalent to ranges::advance(i, bound - i).
  • Otherwise, repeatedly increments iter until it reaches bound. If [iter, bound) is not a valid range, the behavior is undefined in this case.
3) iter is modified to point at the countth next position, bounded by bound.
  • If S and I model std::sized_sentinel_for<S, I>:
    • If |count|<|bound - iter|, equivalent to ranges::advance(iter, bound).
    • Otherwise, equivalent to ranges::advance(iter, count).
  • Otherwise, repeatedly increments or decrements iter by |count| steps, or until iter == bound, whichever comes first.

If one of the following condition is satisfied, the behavior is undefined:

  • count is positive, and [iter, bound) is not a valid range.
  • count is zero, and neither [iter, bound) nor [bound, iter) is a valid range.
  • count is negative, and any of the following conditions is satisfied:
    • [bound, iter) is not a valid range.
    • I does not model bidirectional_iterator.
    • std::same_as<I, S> is not modeled.

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

Parameters

iter - iterator to be advanced
count - the maximum number of steps to increment
bound - the boundary of incrementation

Return value

3) The difference between count and the actual distance iter traversed.

Complexity

1) Linear in |count|, or constant if I models random_access_iterator.
2) Linear in ranges::distance(iter, bound), or constant if any of the following conditions is satisfied:
  • I and S model std::assignable_from<I&, S>.
  • S and I model std::sized_sentinel_for<S, I>, and I models random_access_iterator.
3) Linear in the lesser of the absolute values of count and ranges::distance(iter, bound), or constant if S and I model std::sized_sentinel_for<S, I> and one of the following conditions is satisfied:
  • |count|<|bound - iter|, and I models random_access_iterator.
  • |count|≥|bound - iter|, and any of the following conditions is satisfied:
    • I and S model std::assignable_from<I&, S>.
    • S and I model std::sized_sentinel_for<S, I>, and I models random_access_iterator.

Notes

The behavior is undefined if the specified sequence of increments or decrements would require that a non-incrementable iterator (such as the past-the-end iterator) is incremented, or that a non-decrementable iterator (such as the front iterator or the singular iterator) is decremented.

Possible implementation

struct advance_fn
{
    template<std::input_or_output_iterator I>
    constexpr void operator()(I& iter, std::iter_difference_t<I> count) const
    {
        if constexpr (std::random_access_iterator<I>)
            iter += count;
        else
        {
            while (n > 0)
            {
                --count;
                ++iter;
            }
            
            if constexpr (std::bidirectional_iterator<I>)
            {
                while (count < 0)
                {
                    ++count;
                    --iter;
                }
            }
        }
    }
    
    template<std::input_or_output_iterator I, std::sentinel_for<I> S>
    constexpr void operator()(I& iter, S bound) const
    {
        if constexpr (std::assignable_from<I&, S>)
            iter = std::move(bound);
        else if constexpr (std::sized_sentinel_for<S, I>)
            (*this)(iter, bound - iter);
        else
            while (iter != bound)
                ++iter;
    }
    
    template<std::input_or_output_iterator I, std::sentinel_for<I> S>
    constexpr std::iter_difference_t<I>
        operator()(I& iter, std::iter_difference_t<I> count, S bound) const
    {
        if constexpr (std::sized_sentinel_for<S, I>)
        {
            // std::abs is not constexpr until C++23
            auto abs = [](const std::iter_difference_t<I> x) { return x < 0 ? -x : x; };
            
            if (const auto dist = abs(n) - abs(bound - iter); dist < 0)
            {
                (*this)(iter, bound);
                return -dist;
            }
            
            (*this)(iter, count);
            return 0;
        }
        else
        {
            while (count > 0 && iter != bound)
            {
                --count;
                ++iter;
            }
            
            if constexpr (std::bidirectional_iterator<I>)
            {
                while (count < 0 && iter != bound)
                {
                    ++count;
                    --iter;
                }
            }
            
            return count;
        }
    }
};

inline constexpr auto advance = advance_fn();

Example

#include <iostream>
#include <iterator>
#include <vector>

int main()
{
    std::vector<int> v{3, 1, 4};
    auto vi = v.begin();
    
    std::ranges::advance(vi, 2);
    std::cout << "1) value: " << *vi << '\n' << std::boolalpha;
    
    std::ranges::advance(vi, v.end());
    std::cout << "2) vi == v.end(): " << (vi == v.end()) << '\n';
    
    std::ranges::advance(vi, -3);
    std::cout << "3) value: " << *vi << '\n';
    
    std::cout << "4) returns: " << std::ranges::advance(vi, 2, v.end())
              << ", value: " << *vi << '\n';
    
    std::cout << "5) returns: " << std::ranges::advance(vi, 4, v.end())
              << ", vi == v.end(): " << (vi == v.end()) << '\n';
}

Output:

1) value: 4
2) vi == v.end(): true
3) value: 3
4) returns: 0, value: 4
5) returns: 3, vi == v.end(): true

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 3306 C++20 overload (2) always required [iter, bound) to be valid only required in the step-by-step increment case

See also

advances an iterator by given distance
(function template) [edit]
increment an iterator by a given distance or to a bound
(algorithm function object)[edit]
decrement an iterator by a given distance or to a bound
(algorithm function object)[edit]