Search code examples
c++dictionarykeycode-cleanup

How to properly check keys in a map c++


I have been using maps lately and wanted to know how to check for existing keys in a map. This is how I would add/update keys:

map<int> my_map;
my_map[key] = value;

The [] operator adds a new key if one doesn't exists. If I were to check for a key like this,

map<int> my_map;
if(check_value == my_map[key]){....}

Would this condition return false and also add a new key to my_map. If so, would it be cleaner to add the following check before doing anything with the [] operator (possibly add a helper function that always does this for you).

if(my_map.find(key) == my_map.end()) {
    if(check_value == my_map[key]){....}
}

I realize I kinda answered my own question here but is there a cleaner way to achieve this? Or to not use the [] altogether? Links and tutorials are appreciated.

Thank you.


Solution

  • In C++20, there is std::map::contains, which returns a bool.

    if ( my_map.contains(key) ) { ... }
    

    Before C++20, there is also std::map::count, which (unlike std::multimap::count) can only ever return 0 or 1.

    if ( my_map.count(key) ) { ... }