lundi 26 février 2018

overloading () operator for unordered_set

I have a class, whose objects I put into a unordered_set. To do this I have written custom hash generators and comparators to be able to use the class objects in unordered_set. Everything works fine. The comparator of this class looks like this :

struct MyClassComparator
{
  bool
  operator()(const MyClass & obj1, const MyClass & obj2) const
  {
    if (obj1.getName() == obj2.getName())
      return true;
    return false;
  }
};

So I am comparing the names (strings) of the objects (nothing fancy). I use this to find a MyClass object in a set using .find function.

Now the question is : Is it possible to over load this () operator resulting in the following code

struct MyClassComparator
{
  bool
  operator()(const MyClass & obj1, const MyClass & obj2) const
  {
    if (obj1.getName() == obj2.getName())
      return true;
    return false;
  }

  bool
  operator()(const MyClass & obj1, const std::string & name) const
  {
    if (obj1.getName() == name)
      return true;
    return false;
  }
};

and use the .find function like

my_set.find("my_class_name")

if yes is there a performance overhead in doing so.

Aucun commentaire:

Enregistrer un commentaire