Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is begin() needed in std::vector erase?

Why do we have to write v.erase(v.begin(), v.begin()+3) ?

Why isn't it defined as erase(int, int) so you can write v.erase(0,2) and the implementation takes care of the begin()s?

like image 972
NoComprende Avatar asked Feb 05 '23 17:02

NoComprende


2 Answers

The interface container.erase(iterator, iterator) is more general and works for containers that don't have indexing, like std::list. This is an advantage if you write templates and don't really know exactly which container the code is to work on.

The original design aimed at being as general as possible, and iterators are more general than indexes. The designers could have added extra index-based overloads for vector, but decided not to.

like image 55
Bo Persson Avatar answered Feb 08 '23 17:02

Bo Persson


In STL, iterators are the only entity that provides general access to STL containers.

The array data structure can be accessed via pointers and indexes. iterators are generalization of these indexes/pointers.
Linked list can be accessed with moving pointers (a la ptr = ptr->next). iterators are generalization to these.
Trees and HashTables need special iterator class which encapsulates the logic of iterating these data structures.

As you can see, iterators are the general type which allows you to do common operations (such as iteration, deletion etc.) on data structures, regardless their underlying implementation.

This way, you can refactor your code to use std::list and container.erase(it0, it1) still works without modifying the code.

like image 29
David Haim Avatar answered Feb 08 '23 16:02

David Haim