我有一个 map 输入,其中包含单词列表及其计数。
我使用这个函数来打印 map
输入:
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;
}
它像这样打印值:
你:296
她:14
去:29
如何按字数降序打印。
最佳答案
尝试以下操作:
// 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;
map 根据键排序,i。 e.按字母顺序排列。你无法改变这种行为。因此,完成工作的最简单方法是将其复制到 vector 中并使用用户定义的比较函数对其进行排序。
关于c++ - 在 C++ 中按降序打印 map 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34403415/