计算出现次数并使用C/STL打印顶部K
Count the occurrences and print top K using C/STL
我有一个大的文本文件,每行都有标记。我想统计每个令牌的出现次数并对其进行排序。我如何在C++中高效地做到这一点——最好使用内置函数和最短的编码(当然也是最高效的)?我知道如何在python中做到这一点,但不知道如何在STL中使用unordered_map。
我会采用无序映射方法。为了选择最频繁的k个令牌,假设k小于令牌的总数,您应该查看std::partial_sort。
顺便说一句,++frequency_map[token]
(其中frequency_map是,比如说std::unordered_map<std::string, long>
)在C++中是完全可以接受的,尽管我认为Python中的等价物会在新出现的令牌上爆炸。
好的,给你:
void most_frequent_k_tokens(istream& in, ostream& out, long k = 1) {
using mapT = std::unordered_map<string, long>;
using pairT = typename mapT::value_type;
mapT freq;
for (std::string token; in >> token; ) ++freq[token];
std::vector<pairT*> tmp;
for (auto& p : freq) tmp.push_back(&p);
auto lim = tmp.begin() + std::min<long>(k, tmp.size());
std::partial_sort(tmp.begin(), lim, tmp.end(),
[](pairT* a, pairT* b)->bool {
return a->second > b->second
|| (a->second == b->second && a->first < b->first);
});
for (auto it = tmp.begin(); it != lim; ++it)
out << (*it)->second << ' ' << (*it)->first << std::endl;
}
假设您知道如何在C++中读取文件中的行,这应该是朝着正确的方向推动
std::string token = "token read from file";
std::unordered_map<std::string,int> map_of_tokens;
map_of_tokens[token] = map_of_tokens[token] + 1;
然后你可以将它们打印出来(用于测试):
for ( auto i = map_of_tokens.begin(); i != map_of_tokens.end(); ++i ) {
std::cout << i->first << " : " << i->second << "n";
}
相关文章:
- 我们如何打印出C++ STL 容器的value_type?
- 使用 Boost HOF 实现 STL 漂亮打印
- 无法在STL中打印一组矢量的元素
- 当遇到不是来自 STL 的未捕获异常时,有没有办法打印其信息?
- c++ stl 如何unordered_map打印其所有值?
- 打印/修改类对象的特定成员变量,其类定义列表 (STL) 包含的元素类型
- 从 STL 优先级队列C++ (QtCreator) 打印结构
- 如何在 STL 中使用reverse_iterator打印单词
- 使用队列和列表 STL 进行C++分配。在将数据填充到列表或队列中然后打印该数据时遇到问题
- 漂亮的打印不适用于C ++ STL列表
- 打印列表列表C++ STL 列表
- 计算出现次数并使用C/STL打印顶部K
- C++打印 STL 列表上的数据
- 我可以用cout而不是迭代器循环打印STL映射吗?
- 以二进制模式打印到STL(立体光刻)文件
- STL正确使用find_if()打印奇数
- 打印任何STL容器
- 从STL复制函数以打印出矢量
- 如何迭代地打印SET (STL)中的元素
- 打印/调试libc++ STL与Xcode/LLDB