计算出现次数并使用C/STL打印顶部K

Count the occurrences and print top K using C/STL

本文关键字:STL 打印 顶部 计算      更新时间:2023-10-16

我有一个大的文本文件,每行都有标记。我想统计每个令牌的出现次数并对其进行排序。我如何在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";
}