使用'<'运算符而不是'=='运算符的std :: set <Key,Compare,Allocator> :: find()函数背后的直觉是什么?

时间:2019-12-27 11:57:25

标签: c++ stl c++14

为什么一组自定义类(比如说Person)上的find()函数调用不等式运算符'<'而不是'=='。为了说明,我有以下代码,并且我在一组类Person上调用find函数(请参见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;
}

我还在重载运算符'cout'和'<'的定义中编写了==语句。 输出为:

====================TEST2==========
 < operator called
 < operator called
 < operator called
 < operator called
 < operator called
Something random 
 < operator called
 < operator called
 < operator called
Hit any key to continue...

1 个答案:

答案 0 :(得分:3)

因为std::find使用等效而不是相等。等价使用operator<确定两个对象ab是否相同:

!(a < b) && !(b < a) 

ie 如果a不小于b并且b不小于a,则它们相等。 / p>