gpt4 book ai didi

c++ - 在 map 中找到第 N 个最常出现的键

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:46:38 24 4
gpt4 key购买 nike

我有一张 map ,其中包含不同的字符串以及它们出现的次数。我想找到第 N 个最常出现的键并按降序排列它们。是否有可以执行此操作的 STL 函数?如果不是,在 map 容器中执行此操作的有效方法是什么?

数据结构:

map<string, unsigned int>

这是我的 map 示例:

enter image description here

最佳答案

以下内容可能会有所帮助:

struct comp
{
using P = std::pair<const std::string, std::size_t>;
bool operator() (const P&lhs, const P& rhs) const
{
return rhs.second < lhs.second;
}
};

int main(int argc, char *argv[])
{
const std::map<std::string, std::size_t> m = {{"a", 1}, {"b", 4}, {"c", 2}};
std::vector<std::pair<std::string, std::size_t>> res(2);

std::partial_sort_copy (begin(m), end(m), begin(res), end(res), comp());

for (const auto& e : res) {
std::cout << e.first << " " << e.second << std::endl;
}

return 0;
}

输出:

b 4
c 2

关于c++ - 在 map 中找到第 N 个最常出现的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21730164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com