c++ - 如何获取 std::unordered_map 的最大元素?

标签 c++ c++17 unordered-map

我知道如何通过使用 std::max_element 来检索 std::map 的最大元素,但我无法实现相同的效果std::unordered_map 由于容器类型之间的差异。

如何找到 std::unordered_map 中的最大值并返回相应的 std::pair

显示了我当前使用 std::map 执行此操作的方法(基于 this answer )。我似乎无法弄清楚如何为 std::unordered_map 做同样的事情。

template <typename KEY_T, typename VALUE_T>
std::pair<KEY_T, VALUE_T> findMaxValuePair(
    std::map<KEY_T, VALUE_T> const &x)
{
    return *std::max_element(x.begin(), x.end(),
                             [](const std::pair<KEY_T, VALUE_T> &p1,
                                const std::pair<KEY_T, VALUE_T> &p2)
                             {
                                 return p1.second < p2.second;
                             });
}

当我尝试在 std::unorderd_map 上使用上述函数时(将 std::map 替换为 std::unordered_map,我收到一个 Segmentation fault (core dumped)

最佳答案

使代码适用于 unordered_map

在这种情况下,我们实际上只需将类型从 map 更改为 unordered_map 即可。

之前:

template <class Key, class Value>
std::pair<Key, Value> findMaxValuePair(
    std::map<Key, Value> const &x)
{
    return *std::max_element(x.begin(), x.end(),
                             [](const std::pair<Key, Value> &p1,
                                const std::pair<Key, Value> &p2)
                             {
                                 return p1.second < p2.second;
                             });
}

之后:我们将类型更改为unordered_map

template <class Key, class Value>
std::pair<Key, Value> findMaxValuePair(
    std::unordered_map<Key, Value> const &x)
{
    return *std::max_element(x.begin(), x.end(),
                             [](const std::pair<Key, Value> &p1,
                                const std::pair<Key, Value> &p2)
                             {
                                 return p1.second < p2.second;
                             });
}

使代码对两者都有效

我们可以非常简单地编写一个适用于所有标准容器的函数!这将适用于映射、 vector 、列表以及几乎所有定义 begin()end()value_type 的其他内容!

template <class Container>
auto findMaxValuePair(Container const &x)
    -> typename Container::value_type
{
    using value_t = typename Container::value_type;
    const auto compare = [](value_t const &p1, value_t const &p2)
    {
        return p1.second < p2.second;
    };
    return *std::max_element(x.begin(), x.end(), compare);
}

segmentation fault呢? ?

如果映射或容器为空,则此代码可能会出现段错误,这可能是因为您正在访问不属于您的内存;因为 map::end() 指向的内存包含垃圾,然后您尝试从中构造类似字符串的东西,或者因为它表示为空指针。

特别是对于 map ,如果存在内存损坏,也可能导致段错误,尽管无论您尝试如何遍历 map 都是如此。

关于c++ - 如何获取 std::unordered_map 的最大元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55961314/

相关文章:

c++ - unordered_map find() 和 operator []

c++ - 如何使 C++11 函数采用 function<> 参数自动接受 lambdas

c++ - 在 Ubuntu 14.04 LTS 上安装 Qt Creator 3.1.2

c++ - 如何查看NetBeans for C++应用程序中的内存泄漏?

C++ 等价于 Java Map getOrDefault?

c++ - 如何优化在频繁调用的函数中将大型 std::unordered_map 重用为临时函数?

c++ - Xcode - 剖析和优化 C++ 编译时间

c++ winrt uwp 如何从依赖属性中获取值

C++17 复制构造函数,std::unordered_map 上的深度复制

c++ - std::unordered_multimap 的 bucket 是否只包含具有等效键的元素