Why is begin () necessary in erasing std :: vector?

Why should we write v.erase(v.begin(), v.begin()+3)

?

Why is it not defined as erase(int, int)

, so you can write v.erase(0,2)

and the implementation will take care of begin()

s?

+3


source to share


2 answers


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.

+6


source


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.

+1


source







All Articles