![]() |
VOOZH | about |
std::advance and std::next are used to advance the iterator by a certain position, such that we can make the iterator point to a desired position. Although both have same purpose, but their implementation is different from each other. This makes it important for us to understand the difference between the two. In C++11, std::next() will advance by one by default, whereas std::advance() requires a distance.
// Definition of std::advance() template void advance( InputIt& it, Distance n ); it: Iterator to be advanced n: Distance to be advanced
// Definition of std::next() ForwardIterator next (ForwardIterator it, typename iterator_traits::difference_type n = 1); it: Iterator pointing to base position n: Distance to be advanced from base position.
v1 = 1 2 3 v2 = 4 5 6 1 2
Let us see the differences in a tabular form -:
| std::next | std::advance | |
| 1. | It is used to return nth successor of an iterator | It does not have any return type. |
| 2. | It takes two parameters that are -: number of elements and a iterator. | It takes two parameters number of elements and iterator |
| 3. | Its Time complexity in best case is constant | Its Time complexity in best case is constant |
| 4. | Its Time complexity in worst case is linear | Its Time complexity in worst case is linear |