在 std::set 中插入对不一致(无法识别 <pair>.second)

Inserting pair in std::set is inconsistent (doesn't recognize <pair>.second)

如果我添加条件,此代码的执行方式会有所不同:

第一种情况:

#include<bits/stdc++.h>
using namespace std;

struct comp
{
    bool operator()(pair<int,pair<int,int> > a, pair<int,pair<int,int> > b)
    {
        return a.first>b.first;
    }
};

int main()
{
    set<pair<int,pair<int,int>>,comp> s;
    auto d = s.insert({4,{6,10}});
    cout<<(d.first)->first<<" "<<(d.first)->second.first<<" "<<(d.first)->second.second<<endl;
    d = s.insert({4,{0,4}});
    cout<<(d.first)->first<<" "<<(d.first)->second.first<<" "<<(d.first)->second.second<<endl;
}

输出

4 6 10
4 6 10

第二种情况:(条件为.second)

#include<bits/stdc++.h>
using namespace std;

struct comp
{
    bool operator()(pair<int,pair<int,int> > a, pair<int,pair<int,int> > b)
    {
        if(a.first==b.first)
            return a.second.first<b.second.first;
        return a.first>b.first;
    }
};

int main()
{
    set<pair<int,pair<int,int>>,comp> s;
    auto d = s.insert({4,{6,10}});
    cout<<(d.first)->first<<" "<<(d.first)->second.first<<" "<<(d.first)->second.second<<endl;
    d = s.insert({4,{0,4}});
    cout<<(d.first)->first<<" "<<(d.first)->second.first<<" "<<(d.first)->second.second<<endl;
}

输出:

4 6 10
4 0 4

为什么集合在第一种情况下不添加不同的对?我还以为附加条件只决定顺序,不区分元素

您的第一个比较器仅考虑该对中的第一项。当您尝试插入第二对时,它被认为等于已经插入的对,因此没有插入。

相反,您取回了已插入集合中的对象,这是预期的行为。

请记住,根据定义,一个集合只有一个特定对象的实例,您的比较器帮助它说明两个对象如何相互比较。