Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I increment an iterator by just adding a number?

Tags:

c++

iterator

Can I do normal computations with iterators, i.e. just increment it by adding a number?

As an example, if I want to remove the element vec[3], can I just do this:

std::vector<int> vec; for(int i = 0; i < 5; ++i){       vec.push_back(i); } vec.erase(vec.begin() + 3); // removes vec[3] element 

It works for me (g++), but I'm not sure if it is guaranteed to work.

like image 908
Frank Avatar asked Jun 23 '09 14:06

Frank


People also ask

Can I increment an iterator?

If iter is an InputIterator, you can use: ++iter and iter++ to increment it, i.e., advance the pointer to the next element.

What happens if you increment the iterator past the end?

Obviously if the iterator is advanced past the last element inside the loop the comparison in the for-loop statement will evaluate to false and the loop will happily continue into undefined behaviour.

Do all iterators use pointers?

A pointer can point to elements in an array and can iterate through them using the increment operator (++). But, all iterators do not have similar functionality as that of pointers.

How do I assign one iterator to another in C++?

Operator= -- Assign the iterator to a new position (typically the start or end of the container's elements). To assign the value of the element the iterator is pointing at, dereference the iterator first, then use the assign operator.


1 Answers

It works if the iterator is a random access iterator, which vector's iterators are (see reference). The STL function std::advance can be used to advance a generic iterator, but since it doesn't return the iterator, I tend use + if available because it looks cleaner.

C++11 note

Now there is std::next and std::prev, which do return the iterator, so if you are working in template land you can use them to advance a generic iterator and still have clean code.

like image 182
Todd Gardner Avatar answered Oct 16 '22 02:10

Todd Gardner