Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from std::map based on the time of insertion

Tags:

c++

std

map

stdmap

I need to erase elements from an std::map based on the time of insertion (or something else more efficient than that).

The map will probably hold thousands of elements and if I store the time and iterate the map to check each elements time, it will probably end up being quite time consuming.

Does anyone have any good idea how to erase elements from a std::map when they are getting old?

like image 879
theAlse Avatar asked Mar 15 '12 14:03

theAlse


People also ask

How do you remove items from std::map?

map erase() function in C++ STL 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.

How do you delete a map while iterating?

While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry. getKey() method. If the key matches, remove the entry of that iteration from the HashMap using remove() method.


1 Answers

The std::map<> type has no notion of when an element was inserted. It only serves to hold a key / value pair mapping. It also has no notion of insert order so it can't even provide a relative type of insert.

To do what you want you'll need to add an association between the elements and the time they were inserted. If all you want is relative order then you could use a std::queue paired with the map. Every time you insert into the map you insert into the std::queue as well. Elements at front of the queue are older than the back and you can use that for relative age

like image 68
JaredPar Avatar answered Sep 22 '22 00:09

JaredPar