std::advance
From cppreference.com
| Defined in header <iterator>
|
||
template< class InputIt, class Distance >
void advance( InputIt& iter, Distance count );
|
(constexpr since C++17) | |
Increments the given iterator iter by count steps.
If count is negative, the iterator is decremented. If InputIt does not meet the requirements of LegacyBidirectionalIterator, the behavior is undefined in this case.
Parameters
| iter | - | the iterator to be advanced |
| count | - | the number of steps to be advanced |
| Type requirements | ||
-InputIt must meet the requirements of LegacyInputIterator.
| ||
Complexity
Linear in count.
However, if InputIt additionally meets the requirements of LegacyRandomAccessIterator, complexity is constant.
Notes
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, the behavior is undefined.
Possible implementation
See also the implementations in libstdc++ and libc++.
template<class It, class Distance>
constexpr void advance(It& iter, Distance count)
{
using category = typename std::iterator_traits<It>::iterator_category;
static_assert(std::is_base_of_v<std::input_iterator_tag, category>);
auto dist = typename std::iterator_traits<It>::difference_type(count);
if constexpr (std::is_base_of_v<std::random_access_iterator_tag, category>)
iter += dist;
else
{
while (dist > 0)
{
--dist;
++iter;
}
if constexpr (std::is_base_of_v<std::bidirectional_iterator_tag, category>)
while (dist < 0)
{
++dist;
--iter;
}
}
}
|
Example
Run this code
#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++20) |
advances an iterator by given distance or to a given bound (algorithm function object) |
(C++11) |
increment an iterator (function template) |
(C++11) |
decrement an iterator (function template) |
| returns the distance between two iterators (function template) |