Reputation: 1601
I am using a map structure in my program. The key for the structure is the timestamp. The values keep on changing randomly. My main intention of using map was to ensure that the representation of all the values along with their timestamp should be in the descending order, like the latest event should come on top. However, this is not happening. The values are not in the desired (descending) order.
I have declared map structure like
map<time_t, events> eventR;
map<time_t, events>::iterator iterator;
if the events are there {
then iterator=eventR.begin();
for(iterator = eventR.begin(); iterator!=eventR.end(); ++iterator)
{
//Display
}
}
It may be that I have understood map structure wrong, like it doesn't sort necessarily, but I thought if I am using timestamp, so data will be displayed according to latest events. Am I doing something wrong here? Do I have to use different data structure to get desired result?
Thanks
Upvotes: 1
Views: 699
Reputation: 4444
A c++ std::map does guarantee a certain sorting order:
From: http://www.cplusplus.com/reference/stl/map/
Internally, the elements in the map are sorted from lower to higher key value following a specific strict weak ordering criterion set on construction.
Upvotes: 1
Reputation: 477268
Declare your map as: std::map<time_t, events, std::greater<time_t>>
. (Use a typedef
so that it's easier to declare iterators.)
Alternatively, iterate your map in reverse using rbegin()
and rend()
.
Upvotes: 8