Why does the find() function on a set of custom class (let's say Person) calls the inequality operator '<' instead of '==' . To illustrate , i have the following code , and i am calling the find function on a set of class Person (see test2()) . .
#include<iostream>
#include<stdio.h>
#include<string>
#include<set>
using namespace std ;
class Person {
friend ostream & operator<<(ostream &os , const Person p) ;
string name ;
int age;
public :
Person()
:name{"Unknown"}, age{0}{
}
Person(string name , int age )
:name{name}, age{age}
{
}
//OVERLOADED operators
bool operator<(const Person &rhs) const;
bool operator ==(const Person &rhs) const;
};
bool Person::operator<(const Person &rhs) const{
cout<<" < operator called"<<endl;
return this->age < rhs.age;
}
bool Person::operator==(const Person &rhs) const{
cout<<"Equality operator"<<endl;
return (this->age == rhs.age && this->name == rhs.name);
}
ostream & operator<<( ostream &os , const Person p ){
os<<p.name <<":"<<p.age<<endl;
return os;
}
template<class T>
void display(const set<T> &s1){
for (const auto &temp : s1){
cout<<temp <<" ";
}
cout<<endl;
}
void test2(){
cout<<"====================TEST2=========="<<endl;
set<Person> stooges {
{"Larry",2},
{"Moe",1},
{"Curly",3},
};
cout<<"Something random "<<endl;
auto it = stooges.find(Person{"Moe",1}); //Calls the '<' operator
}
int main(){
test2();
return 0;
}
I have also written the cout statements in the definition of overloaded operators '<' and '==' .
And the output reads :
====================TEST2==========
< operator called
< operator called
< operator called
< operator called
< operator called
Something random
< operator called
< operator called
< operator called
Hit any key to continue...
Because std::find uses equivalence not equality. Equivalence uses operator< to determine if two objects a and b are the same:
!(a < b) && !(b < a)
i.e. if a isn't less than b and b isn't less than a then they're equivalent.
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