Samuel Paz
Samuel Paz

Reputation: 243

c++ std set insert not "working"

I'm having some problems with std set. I know that it does not allows you to insert repeated elements and (I think that) my code is not trying to insert repeated elements. But it seems like the set is not inserting both elements. What is the problem? Is the collection considering both elements equal? Why?

#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;
}

Upvotes: 5

Views: 9580

Answers (3)

Praveen
Praveen

Reputation: 9335

In 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)

In your case bool operator< not satisfy the above condition hence set treats them not unique.

Upvotes: 5

CinCout
CinCout

Reputation: 9619

Currently your comparator returns same values for both the inserts. Hence, only one item is successfully inserted. The other is just a duplicate, and is hence, ignored.

Maybe you meant this:

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

Upvotes: 2

R Sahu
R Sahu

Reputation: 206567

For both objects, the value of tam is 2.0. Since the operator< function works with that value, the two objects are considered to be equal.

BTW, using a floating point number to compare two objects is not a good idea. You can get unexpected results due to the imprecise nature of how floating points are represented.

Upvotes: 3

Related Questions