问题描述:

I have a map input which contains a list of words and their counts.

I use this function to print the map input:

template <class KTy, class Ty>

void PrintMap(map<KTy, Ty> map)

{

typedef std::map<KTy, Ty>::iterator iterator;

for (iterator p = map.begin(); p != map.end(); p++)

cout << p->first << ": " << p->second << endl;

}

it prints the values likes this:

you : 296

she : 14

go : 29

how can I print it in descending order of word count.

网友答案:

Try the following:

// Copy it into a vector.
std::vector<std::pair<std::string,int>> vector( map.begin(), map.end() );

// Sort the vector according to the word count in descending order.
std::sort( vector.begin(), vector.end(), 
           []( const auto & lhs, const auto & rhs ) 
           { return lhs.second > rhs.second; } );

// Print out the vector.
for ( const auto & item : vector )
    std::cout << item.first << ": " << item.second << std::endl;        

The map is sorted according to the keys, i. e. alphabetically. You cannot change that behaviour. Therefore, the easiest way to get the job done is copying it into a vector and sorting it with a user defined compare function.

网友答案:

map stores elements sorted by key not by value. Unless you want to change the type of your map, the only way to do it is to sort your elements after getting them out. I think the easiest way to do so is via std::sort

Given that dereferencing an iterator into a map gives a const value_type&, we can take advantage of the reference to avoid actually creating copies of value_type (which is a std::pair<Key, Value>). However, the code will be a little longer than if we wanted to copy:

template <class KTy, class Ty>
void PrintMap(const std::map<KTy, Ty>& map)
{
    using vt = const typename std::map<KTy, Ty>::value_type*;
    std::vector<vt> vec(map.size());
    size_t i = 0;
    for(const auto& keyval : map)
    {
        vec[i++] = &keyval;
    }
    std::sort(std::begin(vec), std::end(vec), [](vt _lhs, vt _rhs){return _lhs->second > _rhs->second;});

    for(const auto& el : vec)
        std::cout << el->first << ": " << el->second << std::endl;
}

With a test

std::map<std::string, int> myMap{{"you", 296}, {"she", 14}, {"go", 29}};
PrintMap(myMap);

Outputs

you: 296

go: 29

she: 14

This should be much faster if your map is of non-trivially copyable elements.

网友答案:

Put data in another container, sort by word count, print.

相关阅读:
Top