0

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.

user010101
  • 25
  • 9
  • Newer versions of the C++ standard add additional methods that benefit specific use cases involving creation and existence of associative containers' keys. See your favorite current C++ standard reference documentation for more information. – Sam Varshavchik Jul 13 '22 at 23:26
  • @user010101 What is the meaning of the inner if statement if(my_map.find(key) == my_map.end()) { if(check_value == my_map[key]){....} } ? – Vlad from Moscow Jul 13 '22 at 23:28
  • Well, as your code already shows, the call to `find` either succeeds or fails. It also returns an iterator that you can use to access the value stored in the map for that key, if any. What else is it that you want to know? – Paul Sanders Jul 13 '22 at 23:30
  • Don't use `operator[]` with `std::map` when searching for items. The `operator[]` will also insert key, value pairs if the key is not found. Better to use the `find` method. – Thomas Matthews Jul 13 '22 at 23:37

1 Answers1

3

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) ) { ... }
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180