C ++: How to set when two elements are equal?

I created a set of C-lines, providing my own comparator function, because I wanted it to accept only the first three characters. Here is 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 the way I wanted it, sorting the lines, adding them as I described in the set_object class. But the interesting part starts when I try to add a line that compares with the one already added. For example, if I try to add “aaab” when there is already “aaa” in the set, it does not add it to the set. If I add “aaab” first, then try adding “aaa”, it only displays “aaab”. But how does he know when they are equal, if I provided only a function that returns true when one of the lines is larger? It should return false when it is equal to or less!

To clarify, this is not a problem, just an attempt to figure out how C ++ works.

+4
source share
4 answers

You are correct that set_object(x, y) returns false, does not say whether x is less than y or they are equal. So then set_object(y, x) calls to find out.

+5
source
 if (!less(first,second) && !less(second,first)) // equivalent! 

If none is smaller than the other, they are equivalent (not equal, there is a very subtle difference).

+2
source

If the element x not larger or smaller than the other element y . this means that x and y same ...

0
source

Elements are considered equivalent if a<b and b<a are false .

See http://www.sgi.com/tech/stl/StrictWeakOrdering.html .

0
source

Source: https://habr.com/ru/post/1333344/


All Articles