我知道如何通过使用 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/