Namespaces
Variants
Views
Actions

std::advance

From cppreference.com
< cpp‎ | iterator
 
 
Iterator library
Iterator concepts
Iterator primitives
Iterator adaptors
Stream iterators
Iterator customization points
Iterator operations
advance
(C++11)
(C++11)
Range access
(C++11)(C++14)
(C++11)(C++14)
(C++17)(C++20)
(C++14)(C++14)
(C++14)(C++14)
(C++17)
(C++17)
 
Defined in header <iterator>
template< class InputIt, class Distance >
void advance( InputIt& it, Distance n );
(until C++17)
template< class InputIt, class Distance >
constexpr void advance( InputIt& it, Distance n );
(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.

Contents

[edit] Parameters

it - iterator to be advanced
n - number of elements it should be advanced
Type requirements
-
InputIt must meet the requirements of LegacyInputIterator.

[edit] Return value

(none)

[edit] Complexity

Linear.

However, if InputIt additionally meets the requirements of LegacyRandomAccessIterator, complexity is constant.

[edit] 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.

[edit] 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 << '\n';
}

Output:

4

[edit] See also

(C++11)
increment an iterator
(function template) [edit]
returns the distance between two iterators
(function template) [edit]