On this page
std::ranges::advance
Defined in header <iterator> |
||
---|---|---|
Call signature | ||
|
(1) | (since C++20) |
|
(2) | (since C++20) |
|
(3) | (since C++20) |
i
for n
times.
i
until i == bound
.
i
for n
times, or until i == bound
, whichever comes first.
If n
is negative, the iterator is decremented. In this case, I
must model std::bidirectional_iterator
, and S
must be the same type as I
if bound
is provided, otherwise the behavior is undefined.
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.
Parameters
i | - | iterator to be advanced |
bound | - | sentinel denoting the end of the range i is an iterator to |
n | - | number of maximal increments of i |
Return value
n
and the actual distance i
traversed.
Complexity
Linear.
However, if I
additionally models std::random_access_iterator
, or S
models std::sized_sentinel_for<I>
, or I
and S
model std::assignable_from<I&, S>
, complexity is constant.
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
|
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) diff: " << std::ranges::advance(vi, 2, v.end())
<< ", value: " << *vi << '\n';
std::cout << "5) diff: " << 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) diff: 0, value: 4
5) diff: 3, vi == v.end(): true
See also
(C++20)
|
increment an iterator by a given distance or to a bound (niebloid) |
(C++20)
|
decrement an iterator by a given distance or to a bound (niebloid) |
(C++20)
|
returns the distance between an iterator and a sentinel, or between the beginning and end of a range (niebloid) |
advances an iterator by given distance (function template) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/iterator/ranges/advance