packetie
packetie

Reputation: 5069

How to overwrite the [] operator of a unordered_map

Would like to check if a key exists in a unordered_map. Currently I use the count() member function. If it's greater than 0, that means the key exists.

Wonder if it's possible to do something like the following:

typedef std::unordered_map< long, long > m;
m[100] = 20;
m[1000] = 200;
...
//get user input x as an integer
if (m[x] == 0) {
    //do something
}

The problem with the above code is that, for a key x that doesn't exist, if (m[x] == 0) will add an entry to the map. What I need is, for the [] operator to return the default value (say "0" when the type is long, int, empty string object if the type is string) if the key doesn't exist (just don't add an entry). In my situation, the value of the unordered_map entries are not zero. Don't know how to overwrite this operator. Any ideas? Thanks.

Upvotes: 0

Views: 930

Answers (2)

Barry
Barry

Reputation: 303057

What I need is, for the [] operator to return the default value (say "0" when the type is long, int, empty string object if the type is string) if the key doesn't exist (just don't add an entry)

You could write such a function yourself - you don't need to override anything:

template <typename K, typename T, typename H, typename KE, typename A>
T value_or_default(const std::unordered_map<K,T,H,KE,A>& map,
                   const K& key,
                   T def = T{})
{
    auto it = map.find(key);
    return it != map.end() ? it->second : def;
}

Upvotes: 3

Puppy
Puppy

Reputation: 146930

Use .find() instead. if (map.find(key) != map.end()) then it exists in the map. Otherwise if (map.find(key) == map.end()) it does not exist.

Upvotes: 3

Related Questions