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

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

本文关键字:lt 识别 gt second pair set std 插入 不一致      更新时间:2023-10-16

如果我添加一个条件,这段代码的性能会有所不同:

第一种情况:

#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

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

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

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

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