Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL vector vs map erase

Tags:

c++

stl

In the STL almost all containers have an erase function. The question I have is in a vector, the erase function returns an iterator pointing to the next element in the vector. The map container does not do this. Instead it returns a void. Anyone know why there is this inconsistancy?

like image 389
Craig H Avatar asked Sep 09 '08 19:09

Craig H


People also ask

Which is faster vector or map?

Firstly, finding an item in a very small vector can easily be faster than the same thing in a map, because all the memory in a vector is always contiguous (and so plays more nicely with computers' caches and such things), and the number of comparisons needed to find something in a vector might be about the same as for ...

What is the difference between map and vector?

- Vectors are used to store contiguous elements like an array. However, unlike arrays, vectors can be resized. Maps on the other hand contain unique key/value pairs and sorted by keys. - For example, a telephone guide where a key would be the name initial and value will be the number.

What is map erase?

map::erase() is a built-in function in C++ STL which is used to erase element from the container. It can be used to erase keys, elements at any specified position or a given range. Parameters: The function accepts one mandatory parameter key which specifies the key to be erased in the map container.

What does vector erase do?

vector::eraseErases the specified elements from the container. 1) Removes the element at pos. 2) Removes the elements in the range [first, last) . Invalidates iterators and references at or after the point of the erase, including the end() iterator.


1 Answers

See http://www.sgi.com/tech/stl/Map.html

Map has the important property that inserting a new element into a map does not invalidate iterators that point to existing elements. Erasing an element from a map also does not invalidate any iterators, except, of course, for iterators that actually point to the element that is being erased.

The reason for returning an iterator on erase is so that you can iterate over the list erasing elements as you go. If erasing an item doesn't invalidate existing iterators there is no need to do this.

like image 195
Rob Walker Avatar answered Sep 18 '22 03:09

Rob Walker