Why is begin () necessary in erasing std :: vector?
The interface is container.erase(iterator, iterator)
more general and works for containers that are not indexed, for example std::list
. This is an advantage if you are writing templates and do not know exactly which container the code should run in.
The original design aims to be as general as possible, and iterators are more general than indexes. The designers could have added additional index overloads for vector
, but decided not to.
source to share
In the STL, iterators are the only object that provides common access to STL containers.
An array data structure can be accessed using pointers and indices. iterators are a generalization of these pointers / pointers.
The linked list can be accessed with moving pointers (a la ptr = ptr->next
). iterators are a generalization to them.
Trees and hash tables need a special iterator class that encapsulates the logic for iterating over these data structures.
As you can see, iterators are a generic type that allows common operations (like iteration, deletion, etc.) to be performed on data structures, regardless of their underlying implementation.
This way you can refactor your code to use std::list
and container.erase(it0, it1)
while it works without changing your code.
source to share