Sorting a std::map by value before output & destroy

后端 未结 5 893
天涯浪人
天涯浪人 2020-12-01 11:30

I\'m aware that map is not prepared to be sorted. It\'s heavily optimized for fast and random key access and actually doesn\'t support std::sort.

My cur

5条回答
  •  孤街浪徒
    2020-12-01 11:58

    May not be the most elegant way, but you can sort them via value in a set as:

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    struct sortPairSecond
    {
       bool operator()(const pair &lhs, const pair &rhs)
       {
           return lhs.second < rhs.second;
       }
    };
    
    
    int main (int argc, char *argv[])
    {
        cout << "Started...\n";
        map myMap;
        myMap["One"]   = 1;
        myMap["Ten"]   = 10;
        myMap["Five"]  = 5;
        myMap["Zero"]  = 0;
        myMap["Eight"] = 8;
    
    
        cout << "Map Order:\n---------------\n";
        set, sortPairSecond > mySet;
        for(map::const_iterator it = myMap.begin(); it != myMap.end(); ++it)
        {
            cout << it->first << " = " << it->second << "\n";
            mySet.insert(*it);
        }
    
        cout << "\nSet Order:\n--------------\n";
        for(set >::const_iterator it = mySet.begin(); it != mySet.end(); ++it)
        {
            cout << it->first << " = " << it->second << "\n";
        }
    
        return 1;
    }
    
    
    

提交回复
热议问题