Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

less than operator is not guaranteeing unicity for set of objects

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading