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

war*_*onk 5 c++ stl c++14

为什么在一组自定义类(假设 Person)上的 find() 函数调用不等式运算符 ' <' 而不是 ' ==' 。为了说明这一点,我有以下代码,我find在一组类 Person(请参阅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;
}
Run Code Online (Sandbox Code Playgroud)

我还在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...
Run Code Online (Sandbox Code Playgroud)

Pau*_*ans 4

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

!(a < b) && !(b < a) 
Run Code Online (Sandbox Code Playgroud)

如果a不小于bb不小于a那么它们是等价的。