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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With