How can I sort an STL map by value?

前端 未结 8 2114
陌清茗
陌清茗 2020-11-27 04:09

How can I implement STL map sorting by value?

For example, I have a map m:

map m;
m[1] = 10;
m[2] = 5;
m[4] = 6;
m[6] =          


        
相关标签:
8条回答
  • 2020-11-27 04:35

    I have found this in thispointer. The example sorts a std::map< std::string,int> by all the int values.

    #include <map>
    #include <set>
    #include <algorithm>
    #include <functional>
    
    int main() {
    
        // Creating & Initializing a map of String & Ints
        std::map<std::string, int> mapOfWordCount = { { "aaa", 10 }, { "ffffd", 41 },
                { "bbb", 62 }, { "ccc", 13 } };
    
        // Declaring the type of Predicate that accepts 2 pairs and return a bool
        typedef std::function<bool(std::pair<std::string, int>, std::pair<std::string, int>)> Comparator;
    
        // Defining a lambda function to compare two pairs. It will compare two pairs using second field
        Comparator compFunctor =
                [](std::pair<std::string, int> elem1 ,std::pair<std::string, int> elem2)
                {
                    return elem1.second < elem2.second;
                };
    
        // Declaring a set that will store the pairs using above comparision logic
        std::set<std::pair<std::string, int>, Comparator> setOfWords(
                mapOfWordCount.begin(), mapOfWordCount.end(), compFunctor);
    
        // Iterate over a set using range base for loop
        // It will display the items in sorted order of values
        for (std::pair<std::string, int> element : setOfWords)
            std::cout << element.first << " :: " << element.second << std::endl;
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-27 04:37

    I wonder how can I implement the STL map sorting by value.

    You can’t, by definition. A map is a data structure that sorts its element by key.

    0 讨论(0)
提交回复
热议问题