Open In App

std::next vs std::advance in C++

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.

  1. Syntactical Difference: Syntax of std::advance and std::next is:
// 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.
  1. Working
    • Argument Modification: std::advance modifies it arguments such that it points to the desired position, whereas, std::next does not modify its argument, infact it returns a new iterator pointing to the desired position. 




// C++ program to demonstrate
// std::advance vs std::next
#include <iostream>
#include <iterator>
#include <deque>
#include <algorithm>
using namespace std;
int main()
{
    // Declaring first container
    deque<int> v1 = { 1, 2, 3 };
 
    // Declaring second container for
    // copying values
    deque<int> v2 = { 4, 5, 6 };
 
    deque<int>::iterator ii;
    ii = v1.begin();
    // ii points to 1 in v1
 
    deque<int>::iterator iii;
    iii = std::next(ii, 2);
    // ii not modified
 
    // For std::advance
    // std::advance(ii, 2)
    // ii modified and now points to 3
 
    // Using copy()
    std::copy(ii, iii, std::back_inserter(v2));
    // v2 now contains 4 5 6 1 2
 
    // Displaying v1 and v2
    cout << "v1 = ";
 
    int i;
    for (i = 0; i < 3; ++i) {
        cout << v1[i] << " ";
    }
 
    cout << "\nv2 = ";
    for (i = 0; i < 5; ++i) {
        cout << v2[i] << " ";
    }
 
    return 0;
}

v1 = 1 2 3
v2 = 4 5 6 1 2 
  1. Pre-requisite: std::next requires the iterator passed as argument to be of type at least forward iterator, whereas std::advance does not have such restrictions, as it can work with any iterator, even with input iterator or better than it.

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

Article Tags :