Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've 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 map it as a key and with a bool value.

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 ??

like image 389
jbsu32 Avatar asked Dec 18 '22 14:12

jbsu32


1 Answers

std::map<Key, Value> internally stores them as std::map<const Key, Value>. The important thing here is that the Key is const.

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

You'll have to specify operator< as const:

bool operator<(const data& other) const { /*...*/ }
                                  ^^^^^
like image 199
Rakete1111 Avatar answered Dec 24 '22 01:12

Rakete1111