Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why map.erase returns iterator?

Tags:

c++

erase

stdmap

I've want to erase the elements of the std::map from beginIt to endIt. erase function returns the iterator to the element that follows the last element removed. isn't it endIt ? Why the erase returns iterator ?

auto it = m_map.erase(beginIt, endIt);
like image 601
Gevorg Adamyan Avatar asked Mar 24 '16 19:03

Gevorg Adamyan


People also ask

What does Map erase return?

Return Value: The function does not returns anything. It removes all the elements in the given range of iterators.

Does Map return an iterator?

map() loops over the items of an input iterable (or iterables) and returns an iterator that results from applying a transformation function to every item in the original input iterable.

How to erase from Map using iterator?

Erase Element from Map by Iterator std::map provides a erase function that accepts the Iterator and removes the element pointed by the iterator. iterator erase (const_iterator position); It returns the iterator of the next element.

Does Map erase deallocate memory?

No it doesn't free the memory if it is a naked pointer. You need to ensure that the memory is deallocated appropriately.


1 Answers

It's a useful feature that the C++ standard library adopts for all its containers.

One good use in particular is when you are deleting a set of elements subject to a constraint and you are iterating over the whole container. Obviously deleting something from a container invalidates the iterator that you passed. To return the next candidate iterator is useful.

like image 119
Bathsheba Avatar answered Sep 19 '22 22:09

Bathsheba