pat*_*tyx 1 c++ unordered-map c++17
我知道如何std::map通过使用检索 a 的最大元素std::max_element,但std::unordered_map由于容器类型之间的差异,我无法使用 a 实现相同的效果。
如何找到 a 中的最大值std::unordered_map并返回相应的std::pair?
显示了我当前使用 a 执行此操作的方法std::map(基于此答案)。我似乎无法弄清楚如何对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;
});
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在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;
});
}
Run Code Online (Sandbox Code Playgroud)
之后:我们将类型更改为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;
});
}
Run Code Online (Sandbox Code Playgroud)
我们可以非常简单地编写一个适用于所有标准容器的函数!这将为地图,矢量,列出工作,和几乎所有其他定义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);
}
Run Code Online (Sandbox Code Playgroud)
如果地图或容器为空,此代码可能会出现分段错误,因为您正在访问不属于您的内存;因为指向的内存map::end()包含垃圾,然后您尝试从中构造类似字符串的内容,或者因为它表示为空指针。
特别是对于地图,如果内存损坏,也可能导致分段错误,尽管这与您尝试迭代地图的方式无关。
| 归档时间: |
|
| 查看次数: |
4697 次 |
| 最近记录: |