C++ 查找 map 的第 N 个最高元素

标签 c++ sorting vector hashmap

我有一个字符串 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;  
    }
}

Demo

关于C++ 查找 map 的第 N 个最高元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42176254/

相关文章:

C++ boost::spirit 解析嵌入式语言

C++ 库比较 : Boost and Tr1

c++ - 堆栈对象的动态转换失败

c++ - 在运行时将指针推送到 vector C++

c++ - 什么会导致 C++ 中的纯虚函数调用?

sorting - assembly 中的选择排序过程

php - 从 array_count_values 中提取信息

arrays - 尽可能使用 `Iterator` 而不是 `Vec`?

java - 如何在Java中存储 vector ?数据类型是什么?

python - Python中的JSON输出排序