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:

  1. We include the necessary header files: <iostream>, <map>, and <functional>. These headers provide the necessary components for using the map data structure and the greater function object.

  2. We define the main function, which is the entry point of our program.

  3. We declare a map named myMap with key type int, value type std::string, and a custom comparator std::greater<int>. This comparator ensures that the map is sorted in descending order based on the keys.

  4. We populate the map with key-value pairs using the square bracket notation. In this example, we assign the keys 1, 2, 3, 4, and 5 to the corresponding string values.

  5. 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.

  6. Inside the loop, we print the key and value of each pair using std::cout. The pair.first represents the key, and pair.second represents the value.

  7. Finally, we return 0 from the main 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.