Advance iterator for the std::vector std::advance VS operator +?
Adding will only work with random access iterators. std::advance
will work with all sorts of iterators. As long as you're only dealing with iterators into vectors, it makes no real difference, but std::advance
keeps your code more generic (e.g. you could substitute a list
for the vector
, and that part would still work).
For those who care, the standard describes advance
and distance
as follows (§24.3.4/1):
Since only random access iterators provide + and - operators, the library provides two function templates
advance
anddistance
. These function templates use+
and-
for random access iterators (and are, therefore, constant time for them); for input, forward and bidirectional iterators they use++
to provide linear time implementations.
Also note that starting with C++11, the standard added a parameter to std::next
, so you can advance by a specified amount using it (and std::prev
similarly). The difference from std::advance
is that it returns the modified iterator (which std::advance
doesn't), which can be convenient in some cases.
That depends on what you need:
If you need genericity, use std::advance(it,2)
. If someone comes along and changes your std::vector
into a std::list
, the code will still compile, even though advancing now takes linear time instead of constant time.
If you need performance, use it+=2
. If someone comes along and changes your std::vector
into a std::list
, the code will fail to compile, pointing (maybe with a helpful comment) at a serious performance issue.