Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the intution behind std::set<Key,Compare,Allocator>::find() function using the '<' operator instead of '==' operator?

Tags:

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...
like image 962
warrior_monk Avatar asked Dec 27 '19 11:12

warrior_monk


1 Answers

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.

like image 149
Paul Evans Avatar answered Oct 12 '22 21:10

Paul Evans