How can I find the minimum value in a map?

前端 未结 5 1751
夕颜
夕颜 2020-12-05 23:49

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

        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 00:41

    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.

提交回复
热议问题