On this page
std::advance
Defined in header <iterator> |
||
---|---|---|
|
(until C++17) | |
|
(since C++17) |
Increments given iterator it
by n
elements.
If n
is negative, the iterator is decremented. In this case, InputIt
must meet the requirements of LegacyBidirectionalIterator, otherwise the behavior is undefined.
Parameters
it | - | iterator to be advanced |
n | - | number of elements it should be advanced |
Type requirements | ||
-InputIt must meet the requirements of LegacyInputIterator. |
Return value
(none)
Complexity
Linear.
However, if InputIt
additionally meets the requirements of LegacyRandomAccessIterator, 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
See also the implementations in libstdc++ and libc++.
Non-constexpr version |
---|
|
constexpr version |
|
Example
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v{3, 1, 4};
auto vi = v.begin();
std::advance(vi, 2);
std::cout << *vi << ' ';
vi = v.end();
std::advance(vi, -2);
std::cout << *vi << '\n';
}
Output:
4 1
See also
(C++11)
|
increment an iterator (function template) |
(C++11)
|
decrement an iterator (function template) |
returns the distance between two iterators (function template) |
|
(C++20)
|
advances an iterator by given distance or to a given bound (niebloid) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/iterator/advance