Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map - erase last element

Tags:

c++

map

stl

erase

My map is defined as such: map<string, LocationStruct> myLocations; where the key is a time string

I am only keeping 40 items in this map, and would like to drop off the last item in the map when i reach 40 items. I know that i can't do myLocations.erase(myLocations.end()), so how do i go about this?

I do intend for the last item in the map to be the oldest, and therefore FIFO. The data will be coming in rather quick (about 20Hz), so i'm hoping that the map can keep up with it. I do need to look up the data based on time, so i really do need it to be the key, but i am open to alternate methods of accomplishing this.

The format of the string is a very verbose "Thursday June 21 18:44:21:281", though i can pare that down to be the seconds since epoch for simplicity. It was my first go at it, and didn't think too much about the format yet.

like image 754
Jason Avatar asked Jun 21 '12 17:06

Jason


People also ask

How do you delete the last element of a map?

using iterator– : Set an iterator to mp. end() and then use iterator– to get to the last element in the map and then delete it using erase function.

How do I remove something from a map in C++?

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.

How do you delete the last element of a list in C++?

pop_back() : This function removes the last element from the list.

How do you delete a map value?

Map. clear() removes all key-value pairs of the map and reduces the size of the map to zero. Whereas Map. erase() removes the specified mapped value whose key is passed as an argument or iterator or in range to remove pairs.


1 Answers

The most idiomatic way would be:

myLocations.erase( std::prev( myLocations.end() ) );

If you don't ha ve C++11, use the corresponding function from your toolbox.

like image 126
James Kanze Avatar answered Oct 11 '22 14:10

James Kanze