Suppose I want to put objects that identify a server into a stl set
. Then I would have to make sure that I also implement operator<
for these objects otherwise I would run into a compiler error:
struct ServerID
{
std::string name; // name of the server
int port;
};
std::set<ServerID> servers; // compiler error, no operator< defined
This is just one example of a common problem where I want to make an object comparable.
My current solution usually goes like this:
bool operator< (const ServerID & lhs, const ServerID & rhs)
{
if (lhs.name != rhs.name)
{
return lhs.name < rhs.name;
}
else
{
return lhs.port < rhs.port;
}
}
This is just a solution that I found myself. But I suspect that this problem might also have been recognized in computer science. So if I'm lucky there is a better solution for this. Can anyone hint me towards that?