I have a map and I want to find the minimum value (right-hand side) in the map. Here is how I did it:
bool compare(std::pair
The problem is that this:
bool MyClass::compare
Requires an instance of the class to be called on. That is, you can't just call MyClass::compare, but you need someInstance.compare. However, min_element needs the former.
The easy solution is to make it static:
static bool MyClass::compare
// ...
min_element(mymap.begin(), mymap.end(), &MyClass::compare);
This no longer requires an instance to be called on, and your code will be fine. You can make it more general with a functor, though:
struct compare2nd
{
template
bool operator()(const T& pLhs, const T& pRhs)
{
return pLhs.second < pRhs.second;
}
};
min_element(mymap.begin(), mymap.end(), compare2nd());
All this does is grab the second from each pair and grab them, works with any pair. It could be made for general, but that's a bit too much.
If you need to look up by value enough, I recommend you use Boost's Bimap. It's a bi-directional map, so both the key and value can be used to lookup. You would simply get the front of the value-key map.
Lastly, you can always just keep track of the minimum element going into your map. Every time you insert a new value, check if it's lower than your current value (and that should be probably be a pointer to a map pair, start it as null), and if it's lower, point to the new lowest. Requesting the lowest becomes as simple as dereferencing a pointer.