当键相等时 std::multimap 的自定义比较函数

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

我想为 std::multimap 编写自定义比较器。我想做的是比较 keys,如果它们相等,则比较 values。我试图通过在结构中重载 operator() 并将函数对象作为 std::multimap 构造函数中的第三个参数传递来实现。

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;

如果两者都是 int,我如何访问值,而不仅仅是键?

您可以通过std::multiset<std::tuple<int, int>>达到您想要的效果。不需要自定义比较器,因为 std::tuple 使用词典比较(您正在尝试实现的那个)。

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

不,您不能根据 std::multimap 进行比较。

我建议改用 std::vector< std::pair<int, int> > 并简单地排序。 std::pairoperator<会满足你的需求

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:看了另一个答案(即std::multiset<std::tuple<int, int>>),我在想,std::multiset::insert有多糟糕。

然后我想出了下面的基准,它表明,为什么在上面的问题中应该 std::vector 排在第一位。

Quick benchmark online here