I have a struct with some members and I have an implemented operator== for it. Is it safe to implement the operator< with the help of operator==? I want to use this struct in a set, and I want to check that this struct is unique.
struct Data
{
std::string str1;
std::string str2;
std::string str3;
std::string str4;
bool operator==(const Data& rhs)
{
if (str1 == rhs.str1
&& str2 == rhs.str2
&& str3 == rhs.str3
&& str4 == rhs.str4
)
return true;
else
return false;
}
// Is this ok??
bool operator<(const Data& rhs)
{
return !this->operator==(rhs);
}
}
So when I insert this struct to a std::set what will happen?
Nope, it’s quite unsafe. The simplest way to implement it is through
std::tie.