I have a question on how the objects stored in set are compared.
class A
{
public:
char * name;
};
I am storing objects of A in a set. I am provide a comparator class which provides implementation of operator() ( A &ob1, A & ob2 ). Here I compare ob1.name & ob2.name and return true when ob1.name is lesser than ob2.name.
Will I be able to search for an object using the find() of set ? I have provided implementation only for operator(). Will this be sufficient ? Could someone explain how find() works in this case ?
Thanks in advance
The function that will be used in
std::set::find()is an instance of theComparatorclass that you declared as a template parameter of your set.Concretely, the comparator instance will be passed to Key objects and should return true if the first is located before the second. So yes, your implementation is fine.
Now, to dig further: if you want to convince yourself, you can dig into the source code of gcc’s implementation of the standard library, and you’ll find:
You can see that
_M_key_compare(which is an instance of the_Compareclass you provided), is called with__kas a first parameter (one of yourKey) and the return value of_S_key(...)which is a key. The return value of_M_key_compareis used in a ternary expression, so it should be a boolean.