我有一个字符串 vector std::vector<string> list
我正在尝试找到 vector 的第 N 个最高重复元素。
我得到了一张 map ,其中包含 vector 元素及其重复次数。
std::map<std::string , int> mapa;
for(int i = 0 ; i<list.size() ; i++)
mapa[list[i]]++;
如何从 map 中找到第 N 个最高的?
示例 vector :
qwe asd qwe asd zxc asd zxc qwe qwe asd sdf asd fsd
如果 N 是 2,我需要一个像这样的输出
asd 5
qwe 4
最佳答案
您可能会使用 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;
}
}
关于C++ 查找 map 的第 N 个最高元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42176254/