gewizz
gewizz

Reputation: 539

C++ boost unordered_map - determine if key exists in container

In boost::unordered_map how do I determine if a key exists in it or not?

boost::unordered_map<vector<int>, MyValueType> my_hash_map;

if (my_hash_map[non-existent key] == NULL)

The above gets compiler error "no match for operator '=='..."

Is the problem that I am using a custom value type or something else?

Upvotes: 22

Views: 25107

Answers (2)

dalle
dalle

Reputation: 18507

exist() is spelled count() for any associative container:

if (my_hash_map.count(key)) { /*key exist*/ }

if (!my_hash_map.count(key)) { /*key does not exist*/ }

Upvotes: 26

Luk&#225;š Lalinsk&#253;
Luk&#225;š Lalinsk&#253;

Reputation: 41306

You can use the find method:

if (my_hash_map.find(non-existent key) == my_hash_map.end())

Upvotes: 32

Related Questions