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

4.9k Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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

1
On

You can achieve the desired effect with std::multiset<std::tuple<int, int>>. No custom comparator is necessary because std::tuple uses lexicographical comparison (the one you are trying to implement).