I'm working with C++11 and I want to use set to store my custom objects because I need a container, which can filter the elements with the same value.
Here is my class of my custom object:
struct Ele
{
int a, b, c;
}
As my understanding, I need to overload the function operator== because set need to filter the elements with the same value.
However, after reading this link: How do i insert objects into STL set, it seems that overloading operator< is what I need, instead of operator==.
So I code like this:
struct Ele {
int a, b, c;
friend bool operator<(const Ele &e1, const Ele &e2);
};
bool operator<(const Ele &e1, const Ele &e2)
{
if (e1.a < e2.a) {
return true;
}
if (e1.a == e2.a) {
if (e1.b < e2.b) {
return true;
}
if (e1.b == e2.b) {
if (e1.c < e2.c) {
return true;
}
return false;
}
return false;
}
return false;
}
And do a test as below:
set<Ele> myset;
Ele e1;
e1.a = 1;
e1.b = 2;
e1.c = 3;
Ele e2;
e2.a = 1;
e2.b = 2;
e2.c = 3;
myset.insert(e1);
myset.insert(e2);
cout << myset.size() << endl;
Well, the output is 1, instead of 2, which means that the insertion for e2 failed as expected because the value of e2 is the same with the value of e1.
Now I'm confused.
As my understanding, operator< just told the compiler how to understand e1 < e2, how does compiler know how to understand e1 == e2? What if I want to set such a rule: e1 == e2 only if e1.a == e2.b && e1.b == e2.c && e1.c == e2.a?
Aucun commentaire:
Enregistrer un commentaire