Return other value if key not found in the map

c++, unordered-map

Solution

You may do something like (doesn't insert value in map):

template <typename Key, typename Value>
Value& get_or(std::unordered_map<Key, Value>& m, const Key& key, Value& default_value)
{
    auto it = m.find(key);
    if (it == m.end()) {
        return default_value;
    }
    return it->second;
}

Or if you want to add the value in map if not present:

template <typename Key, typename Value, typename T>
Value& get_or(std::unordered_map<Key, Value>& m, const Key& key, T&& default_value)
{
    return m.emplace(key, std::forward<T>(default_value)).first->second;
}

And use it

int default_value = 42;
auto& result = get_or(my_map, i, default_value);

Problem

I have `unordered map`: ``` static unordered_map<int, long> my_map; auto& result = my_map[i]; ``` If there is no key `i`, result would be `0`. Is it possible to return other value, for example `NULL` or `-MAXINT`?

Original source