Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading == operator in unordered_set

I'm trying to create an unordered_set of Intervals as defined below:

struct Interval {
  unsigned int b;  //begining index
  unsigned int e;  //end index
  bool updated;   //true if concat.  initially false
  int patternIndex;  //pattern index. valid for single pattern
  int proteinIndex;   //protein index.  for retrieving the pattern
};

struct Hash {
  size_t operator()(const Interval &interval) const;
};

struct IntervalEquality {
  bool operator == (Interval const &lhs, Interval const &rhs);
};


bool IntervalEquality::operator == (Interval const &lhs, Interval const &rhs){
  return ((lhs.b == rhs.b) && (lhs.e == rhs.e) && (lhs.proteinIndex == rhs.proteinIndex));
}

size_t Hash::operator()(const Interval &interval) const{
  string temp = to_string(interval.b) + to_string(interval.e) + to_string(interval.proteinIndex);
  return hash<string>()(temp);
}

unordered_set<Interval, Hash> test;

Here, I am declaring the == operator in my header file and defining it in my .cpp file (as I am successfully doing for other operators). When I compile the above code, I get errors about the == operator requiring exactly one argument. E.g., 'bool IntervalEquality::operator==(const Interval&, const Interval&)' must take exactly one argument

If I try to take an alternate route and declare and define == in my header file like so:

bool operator == (Interval const& lhs, Interval const& rhs){
    return (lhs.b == rhs.b) && 
           (lhs.e == rhs.e) && 
           (lhs.proteinIndex == rhs.proteinIndex); 
}

I get errors about multiple definitions of ==

Does anyone have an idea of how I can resolve this? Help much appreciated!

like image 410
user2052561 Avatar asked Feb 25 '26 00:02

user2052561


1 Answers

Change the IntervalEquality::operator== to operator(). Then define your unordered_set like so:

unordered_set<Interval, Hash, IntervalEquality> test;

The problem is that you defined what should be a namespace scope operator== as a member function. Namespace scope equality operators take 2 arguments and compare them. Member function equality operators take 1 argument and compare it to the class which is belongs to.

like image 70
David Avatar answered Feb 26 '26 13:02

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!