简体   繁体   中英

How to sort a map with its maximum value of key in C++

I am trying to sort a map with definition map<double,deque<Object>> with the maximum value of double (key) but by default the map takes the minimum value of key . How can I sort the map by the maximum value of key which is a double .

Thanks in advance

You can't re-sort a map, but you can use a map that sorts itself in the reverse order to the default. std::map has a third template parameter for the comparison functor used for ordering. The default is std::less<key_type> . You can trivially use the reverse ordering by using std::greater<key_type> :

std::map<double, std::deque<Object>, std::greater<double>> m;

The closest you can come to sorting a map is to create a new one based on an original with different sorting criteria:

std::map<double, std::deque<Object>> orig = ....;
std::map<double, std::deque<Object>, std::greater<double>> m(orig.begin, orig.end());

map is a key-value pair, key has to be unique in general, if not then value type could be a vector or list instead of a single typed elemental value like hash_map> where MyType is struct or a class. While querying you search with the key to retrieve the value, no notion of sorting. Otherwise, you need to use a vector instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM