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
?
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.
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.
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.
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().
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With