C++ std set insert not "working" 收藏

c++ std set insert not "working"

我在设置 std 时遇到了一些问题。我知道它不允许您插入重复元素并且(我认为)我的代码不会尝试插入重复元素。但似乎集合没有插入两个元素。问题是什么? collection 考虑到两个元素是否相等?为什么?

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

struct sam{
    double a,b, tam;
    sam(){

    }
    sam(double a1, double b1){
        a = a1;
        b = b1;
        tam = b - a;
    }
    bool operator<(const sam &p) const{
        return tam > p.tam;
    }

};
set<sam> ssw;

int main(void){

    ssw.insert(sam(0,2));
    ssw.insert(sam(4,6));
    cout<<ssw.size()<<"\n"; // prints "1"

    return 0;
}

对于这两个对象,tam 的值为 2.0。由于 operator< 函数使用该值,因此两个对象被认为是相等的。

顺便说一句,使用浮点数来比较两个对象不是一个好主意。由于浮点表示方式的不精确性,您可能会得到意想不到的结果。

目前您的比较器 returns 两个插入的值相同。因此,只有一个项目被成功插入。另一个只是重复项,因此被忽略。

也许你的意思是:

bool operator<(const sam &p) const{
        return ( (a > p.a) || (b > p.b) || (tam > p.tam) );
    }

std::set

In imprecise terms, two objects a and b are considered equivalent (not unique) if neither compares less than the other: !comp(a, b) && !comp(b, a)

在你的情况下 bool operator< 不满足上述条件,因此 set 不对待它们 unique