CKTIS / C++
std::advance: moving an iterator by a distance
std::advance modifies an iterator passed by reference, moving it by n positions. It performs no bounds check and returns void.
Version: C++23
Syntax
template<class InputIt, class Distance>
constexpr void advance(InputIt& it, Distance n);std::advance from <iterator> changes it as if it had taken n steps. A random-access iterator can use it += n in constant time; weaker categories require repeated increments, and a bidirectional iterator handles negative n with decrements.
Use it when the iterator object itself should move. If the original must remain unchanged, std::next more clearly returns a new iterator. Complexity is linear except for random access.
The function does not know container boundaries. Moving before the beginning or beyond the valid end() position is undefined. A negative distance requires a bidirectional iterator. After changing a container, also ensure the iterator has not been invalidated.
Examples
#include <array>
#include <iostream>
#include <iterator>
int main() {
const std::array values{2, 5, 9};
auto iterator = values.begin();
std::advance(iterator, 2);
std::cout << *iterator << '\n';
}
Result
9
std::advance → 9