I have created a set of C-strings, supplying my own comparator function because I wanted it to only take take the first three characters into account. Here’s its definition:
struct set_object {
bool operator()(const char* first, const char* second) {
return strncmp(first, second, 3) > 0;
}
};
std::set<const char*, set_object> c_string_set;
It works as I wanted it to, sorting the strings as I add them the way I outlined in the set_object class. But the interesting part begins when I try to add a string that compares equal to one already added. For example, if I try to add “aaab” when there is already “aaa” in the set, it doesn’t add it into the set. If I add “aaab” first, then try to add “aaa”, it only lists “aaab”. But how does it know when they are equal if I only provided a function that returns true when one of the strings is greater? It should return false when it’s either equal or smaller!
To clarify, it’s not a problem, just trying to figure out how C++ works.
You’re right that
set_object(x, y)returning false doesn’t say whether x is less than y or they are equal. So set then callsset_object(y, x)to find out.