How can I sort an STL map by value?

前端 未结 8 2234
陌清茗
陌清茗 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:25

    I've just done a similar question in my c++ book. The answer I came up with might not be very efficient though:

    int main()
    {
        string s;
        map counters;
    
        while(cin >> s)
            ++counters[s];
    
        //Get the largest and smallest values from map
        int beginPos = smallest_map_value(counters);
        int endPos = largest_map_value(counters);
    
        //Increment through smallest value to largest values found
        for(int i = beginPos; i <= endPos; ++i)
        {
            //For each increment, go through the map...
            for(map::const_iterator it = counters.begin(); it != counters.end(); ++it)
            {
                //...and print out any pairs with matching values
                if(it->second == i)
                {
                    cout << it->first << "\t" << it->second << endl;
                }
            }
        }
        return 0;
    }
    
    //Find the smallest value for a map
    int smallest_map_value(const map& m)
    {
        map::const_iterator it = m.begin();
        int lowest = it->second;
        for(map::const_iterator it = m.begin(); it != m.end(); ++it)
        {
            if(it->second < lowest)
                lowest = it->second;
        }
        return lowest;
    }
    
    //Find the largest value for a map
    int largest_map_value(const map& m)
    {
        map::const_iterator it = m.begin();
        int highest = it->second;
        for(map::const_iterator it = m.begin(); it != m.end(); ++it)
        {
            if(it->second > highest)
                highest = it->second;
        }
        return highest;
    }
    

提交回复
热议问题