Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advance iterator for the std::vector std::advance VS operator +?

Tags:

c++

stl

I found myself writing the following a lot:

int location =2;
vector<int> vec;
vector<int>::iterator it=vec.begin();

/..../
std::advance(it, location);

instead of

 it= it + 5;

what is the Preferred/Recommended way ?

like image 597
vehomzzz Avatar asked Nov 03 '09 15:11

vehomzzz


People also ask

How do you advance an iterator in C++?

std::advance in C++ std::advance advances the iterator 'it' by n element positions. Syntax : template void advance (InputIterator& it, Distance n); it : Iterator to be advanced n : Number of element positions to advance. This shall only be negative for random-access and bidirectional iterators.

Can we use iterator in vector?

However, if we were using iterators for vectors to access the elements, then just changing the vector to list in the declaration of the iterator would have served the purpose, without doing anything else So, iterators support reusability of code, as they can be used to access elements of any container.


1 Answers

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 and distance. 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.

like image 117
Jerry Coffin Avatar answered Nov 02 '22 19:11

Jerry Coffin