std::advance

Defined in header <iterator>
1
2
template< class InputIt, class Distance >
void advance( InputIt& it, Distance n );

Increments given iterator it by n elements.

If n is negative, the iterator is decremented. In this case, InputIt must meet the requirements of BidirectionalIterator, 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 InputIterator.

Return value

(none).

Complexity

Linear.

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

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#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:

1
4

See also

(C++11)
increment an iterator
(function)
returns the distance between two iterators
(function)
doc_CPP
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.