c++ - 在 C++ 中按降序打印 map 值

标签 c++

我有一个 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/

相关文章:

c++ - 了解位运算及其效果

c++ - 如何使用 C++ win32 Api 拆分字符?

c++ - 重复执行 lambda 函数

c++ - STL中关联数组(map)的速度

c++ - 删除类数组

c++ - 为什么不能给非常量引用赋值?

c++ - 是否所有官方 Qt 二进制文件都使用 -no-exceptions 构建?

c++ - 分部分读取文件,在最后读取的部分之后继续

c++ - 包含 FreeRTOS 时,手动 CubeMX C 到 C++ 项目的转换失败

c++ - 无法解决cocos2dx中的 "error: candidate is:"