Why can't I map structure in C ++?

I declared a structure like this →

struct data{
    int x,y;
    bool operator < (const data& other) {
        return x<other.x or y<other.y;
    }
};

Now I want to mapuse it as a key and value bool.

int main()
{
    data a;
    map<data,bool>mp;
    a.x=12, a.y=24;
    mp[a]=true;
}

The last line gives me this error →

error: passing 'const' as 'this' argument of 'bool data::operator<(const data&)' discards qualifiers

How can i fix this?

+4
source share
1 answer

std::map<Key, Value>internally saves them as std::map<const Key, Value>. It is important that Keywas const.

So, in your example datathere is const, but operator<no! You cannot call the non-const method from a const object, so the compiler complains.

You need to specify operator<how const:

bool operator<(const data& other) const { /*...*/ }
                                  ^^^^^
+10
source

Source: https://habr.com/ru/post/1650865/


All Articles