How cal I use std::map container with key value in descending order.
As an example, if insert the following items:
[2 , 5] [1 , 34] [3 , 67]
They will be ordered in the map like:
position 0: [1, 34] position 1: [2, 5] position 2: [3, 67]
I can iterate through the map reversely, but suppose the next time I am inserting [-1 , 60]. Will it be placed at the first position?
Generally, the default behavior of map and multimap map is to store elements is in ascending order. But we can store element in descending order by using the greater function.
A Map store the elements in the sorted order of keys. For example, we have a map of words and its frequency count as key – value pair i.e. Map internally stores the above elements in sorted order of keys i.e. Therefore, iterating over a map will give pair elements in above order.
toMap() method to get the result in another Map. In order to sort in decreasing order, just reverse the order of Comparator using Collections. reverseOrder() or Comparator. reverse() method of Java 8.
A map can be sorted by keys. The sorting can be ascending or descending. Ascending is the default. Sorting in a map is not always straightforward.
Use a custom comparator when the default order doesn't do it for you.
You pass it as the third template parameter ( that's normally defaulted to std::less<KeyType>
).
In your case, you can use std::greater
:
std::map<int, int, std::greater<int> > m;
Example code:
#include <map> #include <iostream> #include <functional> int main() { std::map<int, int, std::greater<int>> m { {-1, 77}, {0, 42}, {1, 84} }; for (const auto& p : m) std::cout << '[' << p.first << ',' << p.second << "]\n"; }
Resulting output:
[1,84] [0,77] [-1,42]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With