小于运算符不保证对象集的唯一性

less than operator is not guaranteeing uniqueness for set of objects

我正在尝试构造一组称为客人的对象。为此,我重载了小于运算符。问题是我没有得到独特的元素。我不知道为什么。在以下示例中,集合的大小始终为 2。

// Online C++ compiler to run C++ program online
#include <iostream>
#include <set>
#include <string>

class Guest{
    public:
     Guest(const std::string &fn, const std::string &ln, const std::string &em, const std::string &loy):firstname(fn), lastname(ln), email(em),loyalty(loy){}

     std::string firstname;
     std::string lastname;
     std::string email;
     std::string loyalty;
    
};

bool operator<(const Guest& l, const Guest& r){
    return (l.firstname < r.firstname) or ((l.firstname == r.firstname) and
           ((l.lastname < r.lastname) or ((l.lastname == r.lastname) and
           ((l.email < r.email) or ((l.email == r.email) and
           ((l.loyalty < r.loyalty) or ((l.loyalty == r.loyalty))))))));
}

int main() {
    Guest g1("g1","g2","g3","g4");
    Guest g2("g1","g2","g3","g4");
    
    std::set<Guest> guests = {g1,g2};
    std::cout << guests.size() << std::endl; //Size is always 2 in here. It should be 1
    return 0;
}

您应该删除最后一部分 or ((l.loyalty == r.loyalty)),否则当 Guest 的所有数据成员都相等时,operator< 将 return true

bool operator<(const Guest& l, const Guest& r){
    return (l.firstname < r.firstname) or ((l.firstname == r.firstname) and
           ((l.lastname < r.lastname) or ((l.lastname == r.lastname) and
           ((l.email < r.email) or ((l.email == r.email) and
           ((l.loyalty < r.loyalty) ))))));
}

或者使用 std::tie 使其更简单。

bool operator<(const Guest& l, const Guest& r){
    return std::tie(l.firstname, l.lastname, l.email, l.loyalty) < 
           std::tie(r.firstname, r.lastname, r.email, r.loyalty);
}