What's the difference between std::advance and std::next?
Is there more beyond advance takes negative numbers?
Solution 1:
std::advance
- modifies its argument
- returns nothing
- works on input iterators or better (or bi-directional iterators if a negative distance is given)
std::next
- leaves its argument unmodified
- returns a copy of the argument, advanced by the specified amount
- works on forward iterators or better (or bi-directional iterators if a negative distance is given))
Solution 2:
Perhaps the biggest practical difference is that std::next()
is only available from C++11.
std::next()
will advance by one by default, whereas std::advance()
requires a distance.
And then there are the return values:
-
std::advance()
: (none) (the iterator passed in is modified) -
std::next()
: The n th successor.
std::next()
takes negative numbers just like std::advance
, and in that case requires that the iterator must be bidirectional. std::prev()
would be more readable when the intent is specifically to move backwards.