Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between std::advance and std::next?

Tags:

c++

std

c++11

Is there more beyond advance takes negative numbers?

like image 448
Tavison Avatar asked Feb 22 '13 04:02

Tavison


People also ask

Why use std:: advance?

Use std::advance. It is just as efficient (it uses iterator traits to just do iterator addition for random access iterators), and is more general in that it works on other kinds of iterators as well.

What is std advance?

std::advanceAdvances the iterator it by n element positions. If it is a random-access iterator, the function uses just once operator+ or operator- . Otherwise, the function uses repeatedly the increase or decrease operator ( operator++ or operator-- ) until n elements have been advanced.

What does std :: next do?

std::next returns an iterator pointing to the element after being advanced by certain no. of positions. It is defined inside the header file . It does not modify its arguments and returns a copy of the argument advanced by the specified amount.


2 Answers

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))
like image 161
Benjamin Lindley Avatar answered Oct 08 '22 11:10

Benjamin Lindley


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.

like image 35
Johnsyweb Avatar answered Oct 08 '22 12:10

Johnsyweb