您可以使用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'完全一樣。 –