I’m using a map to store a bunch of keys and values. I want to use find() to find the key and return the value. Unfortunately, when I can’t find the key, it get’s upset. How can I make it return 0 if no key is found?
int bag::getItem( const string item)
{
return this->bagItems.find(item)->second;
return 0;
}
Any suggestions would be greatly appreciated.
map::findreturns the value ofmap::end()if the value was not found. That’s an iterator value that you cannot dereference, so blindly doingbagItems.find(item)->secondis a no-no.Instead, check the return value and act accordingly:
To do this, you ‘ll want to have a local variable of
const_iteratortype; however, that type depends on the template arguments of your map (which we don’t know). So you will have to fill the blank in yourself.If you are in the pleasant position of using a C++11 compiler, the convenient
will work.