In this blog post we are going to learn difference between std::advance and c++11 std::next. std::advance and std::next are used to advance the iterator by a certain position. Let us see below example of std::advance

#include<iostream>
#include<list>
#include<iterator>
using namespace std;

int main()
{
    list<int> mylist;

    // push 1,2,3,4,5,6,7,8,9 into list
    for(int i=0; i < 10; i++)
    	mylist.push_back(i);

    list<int>::iterator it = mylist.begin();

    // it will point to first element of list
    cout << *it; // will print 0

    // Let us point to 3rd element
    advance(it,3);

    // Now it will point to 3rd element of list
    cout << *it; // will print 3

	return 0;
}

Let us use std::next in place of advance in above example. See below code.

#include<iostream>
#include<list>
#include<iterator>
using namespace std;

class foo
{
public:
	int mutable mid;
	foo()
	{
		mid = 5;
	}
};

int main()
{
    list<int> mylist;

    // push 1,2,3,4,5,6,7,8,9 into list
    for(int i=0; i < 10; i++)
    	mylist.push_back(i);

    list<int>::iterator it = mylist.begin();

    // it will point to first element of list
    cout << *it;

    // Let us point to 3rd element
    list<int>::iterator itt = next(it,3);

    // it will point to 3rd element of list
    cout << *itt;


	return 0;
}

After looking the above two sample code , we can identify differences as

  • The std::advance returns nothing while std::next returns iterator.
  • The std::next is available in c++11 or c++17. so to compile c++ code in which std::next is used require -std=c++11 switch in g++ compiler.
  • std::advance modifies its argument while std::next  do not.
  • std::next will advance the iterator position by one by default while std::advance do not. so below program will print 1, because when there is no argument supplied to std::next, it will even advances position of iterator by one.
#include<list>
#include<iterator>
using namespace std;

int main()
{
    list<int> mylist;

    // push 1,2,3,4,5,6,7,8,9 into list
    for(int i=0; i < 10; i++)
    	mylist.push_back(i);

    list<int>::iterator it = mylist.begin();

    // Let us point to 3rd element
    list<int>::iterator itt = next(it);

    // it will point to 3rd element of list
    cout << *itt << endl;

	return 0;
}
  • std::next() takes negative numbers just like std::advance, and in that case of negative number, it requires bidirectional iterator.

Ref:

http://en.cppreference.com/w/cpp/iterator/advance

http://en.cppreference.com/w/cpp/iterator/next



Related Contents to follow