Home > front end >  less than operator is not guaranteeing uniqueness for set of objects
less than operator is not guaranteeing uniqueness for set of objects

Time:04-10

I am trying to construct a set of objects called guests. For this purpose, I overloaded the less than operator. The problem is that I'm not getting unique elements. I can't figure out why. The size of the set is always 2 in the following example.

// 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;
}

CodePudding user response:

You should remove the last part or ((l.loyalty == r.loyalty)), otherwise the operator< would return true when all the data members of Guest are equivalent.

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 make it much simpler with 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);
}
  • Related