如何获取列表中出现频率最高的元素?

How to get the most frequent element of a list?

假设我有一个列表:

std::list<std::string> list ("the", "the", "friend", "hello", "the");

在这种情况下,列表中最常见的元素是 "the"。有没有办法在 C++ 中获取这个元素??

谢谢!

解决您的问题的通用算法是构建词频词典。这是一个伪代码算法,正是这样做的:

let L be the input sequence of strings (can be a list, doesn't matter)
let F be an empty dictionary that maps string to a number
for each string S in L
    if not F contains S then
        F[S] = 0
    F[S] += 1

字典构建完成后,您需要做的就是找到具有最高值的映射,return键。

C++ 标准库提供了关联容器(又名字典,又名 maps),以及在容器中搜索最大元素的算法。