Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return other value if key not found in the map

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?

like image 455
kotokbek Avatar asked Oct 20 '16 16:10

kotokbek


People also ask

What happens if key not found in map?

If the key is not present in the map, get() returns null. The get() method returns the value almost instantly, even if the map contains 100 million key/value pairs.

What does std::map return if key not found?

std::map operator[] inserts the default constructed value type in to the map if the key provided for the lookup doesn't exist. So you will get an empty string as the result of the lookup.

What map return if key is not present C++?

If we only want to know the presence of a key in the map container but doesn't want an iterator to it, we can use the count() member function of the map container, which returns the value of 1 if the specified key is found, or 0 if the key is not found.

What happens if key not in map C++?

map find() function in C++ STL If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map. end().


1 Answers

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);
like image 107
Jarod42 Avatar answered Sep 24 '22 00:09

Jarod42