tags:

views:

213

answers:

2

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.

+11  A: 

It works if the iterator is a random access iterator, which vector's iterators are (see references). The STL function 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.

Todd Gardner
Oh, so it wouldn't work for std::list?
Correct; added some documentation links that list which functions should be available to which types of iterators.
Todd Gardner
No, it doesn't. The + operator means "in one step, jump this far ahead" which a list iterator cannot do. Forward non-random-access iterators (like list iterators) support only support the increment (++) operator to advance one element at a time. As Todd said, you can use std::advance, which invokes the ++ operator repeatedly, to succinctly express the idea of moving a non-random iterator forward by a number of steps.
Tyler McHenry
Well, to be pedantic, it isn't guaranteed to work for bidirectional iterators like list, but I believe it isn't guaranteed to not work either; an implementation could add it.
Todd Gardner
+1  A: 

It works with random access iterators. In general you may want to look at std::advance which is more generic. Just be sure to understand performance implications of using this function template.

Nemanja Trifunovic