Search code examples
c++c++11multimapcustom-compare

Custom compare function for std::multimap when keys are equal


I would like to code a custom comparator for a std::multimap. What I would like to do is to compare the keys, in case they are equal, then compare the values. I'm trying to do it by overloading the operator() in a struct and passing the function object as a third parameter in the std::multimap constructor.

struct CustomComp {
    bool operator()(int key_lhs, int key_rhs){
        if (key_lhs < key_rhs) return true;
        if (key_lhs == key_rhs) //Check values;
        else return false;
    }
};

multimap<int, int, CustomComp> myMap;

How can I access the values, not only the keys, if both are int?


Solution

  • What I would like to do is to compare the keys, in case they are equal, then compare the values.

    No, you can not make a comparison for std::multimap according to the values.

    I would suggest using std::vector< std::pair<int, int> > instead and simply sort. The operator< of std::pair will take care of what you want.

    See output here

    std::vector< std::pair<int, int> > vec{ {1,2}, {1,-1},{ 2,2 } ,{ -1,1 } };
    std::sort(std::begin(vec), std::end(vec));
    

    Update: After reading the other answer(i.e, std::multiset<std::tuple<int, int>>), I was thinking about, how bad is the std::multiset::insert.

    Then I came up with the following benchmark, which shows, why should be std::vector at first place in the above problem.

    See Quick benchmark online here

    Vector-Sort Vs Multimap-Insertion