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?
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< ofstd::pair
will take care of what you want.See output here
Update: After reading the other answer(i.e,
std::multiset<std::tuple<int, int>>
), I was thinking about, how bad is thestd::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