I know how to retrieve the maximum element of a std::map
through the use of std::max_element
, but I am unable to achieve the same affect with a std::unordered_map
due to the differences between the container types.
How can I find the maximum value in a std::unordered_map
and return the corresponding std::pair
?
My current method for doing this with a std::map
is shown (based on this answer). I can't seem to figure out how to do the same for a 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;
});
}
When I attempt to use the above function on a std::unorderd_map
(replacing std::map
with std::unordered_map
, I receive a Segmentation fault (core dumped)
.