假设我有一个列表:
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
一旦字典构造完成,您需要做的就是找到具有最高值的映射,并返回键。
C++ 标准库提供了关联容器(又名字典,又名映射),以及一种用于在容器中搜索最大元素的算法。
关于c++ - 如何获取列表中出现频率最高的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42916120/