Let iter be an std::iterator. Is there any difference between std::next(iter,1) and ++iter?

Viewed 149

Please consider the following code:

#include <iostream>
#include <iterator>
#include <vector>

int main() 
{
    std::vector<int> v{1,2,3};

    // implementation 1:
    for(auto iter = v.begin(); iter !=v.end(); ++iter)
        std::cout << *iter;
    std::cout << std::endl;

    // implementation 2:
    for(auto iter = v.begin(); iter !=v.end(); iter = std::next(iter, 1))
        std::cout << *iter;
    std::cout << std::endl;       
}

As you can see here implementation 1 and implementation 2 produce the same output. Is this always the case?

2 Answers

In your code there is no difference. Both will advance the iterator one step.

Just to give one example where it might matter, let's say we want to print the second element of a range, we can't write something like ++b.begin() since we can't apply ++ to an rvalue.

Here a code example.

#include <array>
#include <iostream>

int main()
{
    std::array<int, 2> a = {2, 4};

    //std::cout << *(++a.begin()); // This will fail
    std::cout << *std::next(a.begin());
}

If we uncomment the first output line gcc says

prog.cc: In function 'int main()':
prog.cc:8:29: error: lvalue required as increment operand
    8 |     std::cout << *(++a.begin());
      |                      ~~~~~~~^~

Live example

Yes iter = std::next(iter, 1) is equivalent to ++iter.

The only difference between std::next(iter, 1) and ++iter i can think of is that std::next doesn't modify the iterator it returns the copy of resultant iterator.

Also std::next is very useful in generic context where iterator can be random access , forward etc. it will use most appropriate way to advance the iterator.

Related