unordered_set: invalid operands to binary expression ('const Play' and 'const Play')

StackOverflow https://stackoverflow.com/questions/20135153

  •  03-08-2022
  •  | 
  •  

سؤال

I'm getting this error when I try to insert an element into an unordered_set:

error: invalid operands to binary expression ('const Play' and 'const Play')
        {return __x == __y;}

Here's a screenshot of the whole error: https://www.dropbox.com/s/nxq5skjm5mvzav3/Screenshot%202013-11-21%2020.11.24.png

This is my hash function:

struct Hash {

        size_t operator() (Play &play) {

            unsigned long hash = 5381;
            int c;

            string s_str = play.get_defense_name() + play.get_offense_name() + play.get_description();
            const char * str = s_str.c_str();

            while ( (c = *str++) )
                hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

            cout << hash << endl;
            return hash;

       }
    };

This is where I declare the unordered_list:

unordered_set<Play, Hash> Plays;

And this is my overloaded == for my Play class:

friend bool operator== (Play& p1, Play& p2)
    {
        return 
            (p1.get_defense_name() == p2.get_defense_name()) && 
            (p1.get_offense_name() == p2.get_offense_name()) &&
            (p1.get_description() == p2.get_description()); 
    }

Any idea what could be going on here?

Thanks.

هل كانت مفيدة؟

المحلول

the error is saying it try to compare const Play with const Play but you only provide operator == for Play

friend bool operator== (const Play& p1, const Play& p2)
    {
        return 
            (p1.get_defense_name() == p2.get_defense_name()) && 
            (p1.get_offense_name() == p2.get_offense_name()) &&
            (p1.get_description() == p2.get_description()); 
    }

نصائح أخرى

It looks like unordered set is looking to compare constant Play objects, but your == offers to compare non-const ones. Since dropping const-ness is not allowed, the compiler produces an error. Adding const-ness should fix the problem:

friend bool operator== (const Play& p1, const Play& p2)

You should add const to your operator() as well:

size_t operator() (const Play &play)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top