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!

有帮助吗?

解决方案 2

Put this in the header:

bool operator== (Interval const& lhs, Interval const& rhs);

Put this in the .cpp file:

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

While you can create an equality lambda, in this case this equality makes sense for a general equality.

The only thing I'd be careful of is the fact that your == isn't full equality. If one Interval differs only by updated or patternIndex from another and have a hash collision, they will silently overwrite the other.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top