std::vector::erase will accept either a single iterator denoting the position of the element to be erased, or two iterators denoting a range. But you can’t do this:
std::vector<int> vec = { 1, 2, 3 };
vec.erase(1);
Rather you have to do something like
vec.erase( vec.begin()+1 );
This seems like needless extra work–just wondering, is there some reason from the POV of class design why this overload wouldn’t be included?
Edit: Chose the most comprehensive answer, all were good. Also as I write this this post has 4 close votes for being ‘not constructive’; however, given the quality of the answers I think this was clearly a useful question, certainly for me.
There are two reasons I can think of:
1)
eraseis common member function for containers. Using indices only make sense for some containers, so by using iterators you do not have to worry about the type of container you are working on. For example, indices only make sense for random-access containers, by using iterators you make your code more flexible, etc.2)
eraseworks well with the standard algorithms likestd::remove,std::remove_if,std::unique, etc. It is much more common to want to erase elements based on some predicate, etc. rather than hard coding an index number. Look up “erase-remove idiom” for more information.Basically, iterators are consider to be superior to indexing for many reasons and is what you will see used extensively in the C++ standard library. Indices are merley provided for simulated array access were it makes sense.