map in c++ sorted descending order
#include <iostream>
#include <map>
#include <functional>
int main() {
std::map<int, std::string, std::greater<int>> myMap;
myMap[1] = "one";
myMap[2] = "two";
myMap[3] = "three";
myMap[4] = "four";
myMap[5] = "five";
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
Explanation:
We include the necessary header files:
<iostream>
,<map>
, and<functional>
. These headers provide the necessary components for using themap
data structure and thegreater
function object.We define the
main
function, which is the entry point of our program.We declare a
map
namedmyMap
with key typeint
, value typestd::string
, and a custom comparatorstd::greater<int>
. This comparator ensures that the map is sorted in descending order based on the keys.We populate the map with key-value pairs using the square bracket notation. In this example, we assign the keys
1
,2
,3
,4
, and5
to the corresponding string values.We use a range-based for loop to iterate over the elements of the map. The loop variable
pair
represents each key-value pair in the map.Inside the loop, we print the key and value of each pair using
std::cout
. Thepair.first
represents the key, andpair.second
represents the value.Finally, we return
0
from themain
function, indicating successful program execution.
Note: The std::greater<int>
comparator is used in this example to demonstrate sorting in descending order. If you want to sort the map in ascending order, you can omit the third template argument or use the default std::less<int>
comparator.