Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ std set insert not "working"

Tags:

c++

set

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;
}
like image 654
Samuel Paz Avatar asked Mar 15 '23 23:03

Samuel Paz


1 Answers

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.

like image 149
R Sahu Avatar answered Mar 25 '23 09:03

R Sahu