Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::map items in descending order of keys

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?

like image 791
Sigcont Avatar asked Mar 23 '14 13:03

Sigcont


People also ask

How do I create a map in descending order C++?

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.

Does map store elements in sorted order C++?

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.

How do you find the map in descending 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.

Can we sort map by key in C++?

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.


1 Answers

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] 
like image 126
jrok Avatar answered Oct 05 '22 22:10

jrok