【问题标题】:C++ Find N-th highest element of a mapC ++查找地图的第N个最高元素
【发布时间】:2017-06-29 19:08:23
【问题描述】:

我有一个字符串向量std::vector<string> list,我试图找到向量的第 N 个最高重复元素。

我得到了一张包含向量元素和重复次数的地图。

std::map<std::string , int> mapa;
for(int i = 0 ; i<list.size() ; i++)
  mapa[list[i]]++;

如何从地图中找到第 N 个最高的?

示例向量:

qwe asd qwe asd zxc asd zxc qwe qwe asd sdf asd fsd 

如果 N 为 2,我需要一个类似

的输出
asd 5
qwe 4

【问题讨论】:

  • 你可能想考虑std::unordered_map,而不是sort它的值,并获得第n:第一个元素?
  • @Someprogrammerdude 我没有使用地图的经验,请指导我如何将向量的成员添加到 unordered_map?和地图一样吗?
  • 我建议您点击参考链接。但简而言之,界面和std::map几乎一模一样。
  • 实现您自己的algorithm,如果需要,它的性能可以优于 stl。但它们通常需要对容器进行随机访问。

标签: c++ sorting vector hashmap


【解决方案1】:

你可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多