std::advance() is a utility function provided by the C++ Standard Library that moves an iterator forward or backward by a specified number of positions. It works with all iterator categories and automatically uses the most efficient implementation available for the iterator type.
- Moves an iterator by a specified number of positions.
- Supports input, bidirectional, and random-access iterators.
Example: Advancing an Iterator
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main() {
vector<int> v = {10, 20, 30, 40, 50};
auto it = v.begin();
advance(it, 2);
cout << *it;
return 0;
}
Output
30
Explanation: The iterator initially points to the first element (10). After advancing it by 2 positions, it points to the third element (30).
Syntax
template <class InputIt, class Distance>
void advance(InputIt& it, Distance n);
Parameters
- it: The iterator to be advanced.
- n: The number of positions to move the iterator, positive values move the iterator forward, negative values are allowed only for bidirectional and random-access iterators.
Return Value: std::advance() does not return any value. It directly modifies the iterator passed to it.
Internal Working of std::advance()
The implementation of std::advance() depends on the category of iterator being used:
- Input and Forward Iterators: The iterator is advanced one position at a time.
- Bidirectional Iterators: The iterator can be moved both forward and backward.
- Random-Access Iterators: The iterator is advanced using pointer arithmetic, resulting in constant-time complexity.
Example 1: Printing Alternate Elements
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main() {
vector<int> v;
for (int i = 0; i < 10; i++)
v.push_back(i * 10);
auto it = v.begin();
while (it < v.end()) {
cout << *it << " ";
advance(it, 2);
}
return 0;
}
Output
0 20 40 60 80
Example 2: Moving Backward
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main() {
vector<int> v = {10, 20, 30, 40, 50};
auto it = v.end();
advance(it, -2);
cout << *it;
return 0;
}
Output
40
Complexity of std::advance()
The time complexity of std::advance() depends on the iterator category:
| Iterator Category | Time Complexity |
|---|---|
| Input Iterator | O(n) |
| Forward Iterator | O(n) |
| Bidirectional Iterator | O(n) |
| Random Access Iterator | O(1) |
Applications of std::advance()
std::advance() is commonly used when working with STL containers and generic algorithms that require moving iterators by a specified number of positions.
- Moving iterators without writing explicit loops.
- Working with generic STL algorithms.
- Traversing containers that do not support random access.
- Advancing iterators by a dynamic number of positions.
Related article: std::advance() vs std::next()