linofex linofex - 3 months ago 14
C++ Question

can't I use map [ ] operator with const function keyword?

I have got this function:

bool Table::FindCard(const int& i, const Card& card) const{
std::vector<Card>::const_iterator iter = table[i].begin();
for(; iter != table[i].end() ; ++iter){
if(*iter == card){
return true;
}
}

return false;
}


where Card is a class and Table is a class with:

std::map<int, std::vector<Card> > table;


If I run the code I get this error:

Table.cc: In member function ‘bool Table::FindCard(const int&, const Card&) const’:
Table.cc:42:50: error: passing ‘const t_map {aka const std::map<int, std::vector<Card> >}’ as ‘this’ argument discards qualifiers [-fpermissive]
std::vector<Card>::const_iterator iter = table[i].begin();


But if I delete
const
keyword:

bool Table::FindCard(const int& i, const Card& card){
...
}


all works.

The reason is because operator[] isn't const? I know that a const function can call only other const function.

Thanks

Answer

The reason is because operator[] isn't const? I know that a const function can call only other const function.

Yes; operator[] is specified to create a new default-constructed element if the key doesn't exist, and this wouldn't be sensible on a const map, thus it's not marked as const.

Of course you could specify the const version to throw an exception (as at does) or - I don't know - call terminate if the key isn't found, but alas the standard doesn't say that. You'll either have to use at or (ugh) find.