您可以使用std::partial_sort
:
std::map<std::string, std::size_t>
compute_frequencies(const std::vector<std::string>& words)
{
std::map<std::string, std::size_t> res;
for(const auto& word : words) {
res[word]++;
}
return res;
}
std::vector<std::pair<std::string, std::size_t>>
as_vector(const std::map<std::string, std::size_t>& m)
{
return {m.begin(), m.end()};
}
int main() {
const std::vector<std::string> words{
"qwe", "asd", "qwe", "asd", "zxc", "asd",
"zxc", "qwe", "qwe", "asd", "sdf", "asd", "fsd"
};
auto frequencies = as_vector(compute_frequencies(words));
std::partial_sort(frequencies.begin(), frequencies.end(), frequencies.begin() + 2,
[](const auto& lhs, const auto& rhs) {
return lhs.second > rhs.second;
});
for (std::size_t i = 0; i != 2; ++i) {
std::cout << frequencies[i].first << " " << frequencies[i].second << std::endl;
}
}
Demo
你可能想要con sider ['std :: unordered_map'](http://en.cppreference.com/w/cpp/container/unordered_map),['sort'](http://en.cppreference.com/w/cpp/算法/排序)它的值,并获得第n个第一个元素? –
@Someprogrammerdude我对映射没有经验,请指导我如何将向量的成员添加到unordered_map?和地图一样吗? – ffttyy
我建议您按照参考链接。但总之,这个接口几乎和'std :: map'完全一样。 –