How can I find the minimum value in a map?
In C++11 you can do this:
auto it = min_element(pairs.begin(), pairs.end(),
[](decltype(pairs)::value_type& l, decltype(pairs)::value_type& r) -> bool { return l.second < r.second; });
Or put it in a nice function like this (note I'm not a template guru; this is probably wrong in many ways):
template<typename T>
typename T::iterator min_map_element(T& m)
{
return min_element(m.begin(), m.end(), [](typename T::value_type& l, typename T::value_type& r) -> bool { return l.second < r.second; });
}
With C++14, it further simplifies to:
min_element(pairs.begin(), pairs.end(),
[](const auto& l, const auto& r) { return l.second < r.second; });
You have a few options. The "best" way to do this is with a functor, this is guaranteed to be the fastest to call:
typedef std::pair<std::string, int> MyPairType;
struct CompareSecond
{
bool operator()(const MyPairType& left, const MyPairType& right) const
{
return left.second < right.second;
}
};
int MyClass::getMin(std::map<std::string, int> mymap)
{
std::pair<std::string, int> min
= *min_element(mymap.begin(), mymap.end(), CompareSecond());
return min.second;
}
(You can also nest the CompareSecond
class inside MyClass
.
With the code you have now, you can easily modify it to work, however. Just make the function static
and use the correct syntax:
static bool
MyClass::compare(std::pair<std::string, int> i, std::pair<std::string, int> j)
{
return i.second < j.second;
}
int MyClass::getMin(std::map<std::string, int> mymap)
{
std::pair<std::string, int> min = *min_element(mymap.begin(), mymap.end(),
&MyClass::compare);
return min.second;
}