What happens if I read a map's value where the key does not exist?
The map::operator[]
searches the data structure for a value corresponding to the given key, and returns a reference to it.
If it can't find one it transparently creates a default constructed element for it. (If you do not want this behaviour you can use the map::at
function instead.)
You can get a full list of methods of std::map here:
http://en.cppreference.com/w/cpp/container/map
Here is the documentation of map::operator[]
from the current C++ standard...
23.4.4.3 Map Element Access
T& operator[](const key_type& x);
Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.
Requires: key_type shall be CopyConstructible and mapped_type shall be DefaultConstructible.
Returns: A reference to the mapped_type corresponding to x in *this.
Complexity: logarithmic.
T& operator[](key_type&& x);
Effects: If there is no key equivalent to x in the map, inserts value_type(std::move(x), T()) into the map.
Requires: mapped_type shall be DefaultConstructible.
Returns: A reference to the mapped_type corresponding to x in *this.
Complexity: logarithmic.
What does the STL map[key] return if the key wasn't a initialized key in the map?
A default constructed std::string
ins inserted into the std::map
with key 'b'
and a reference to that is returned.
It is often useful to consult the documentation, which defines the behavior of operator[]
as:
Returns a reference to the object that is associated with a particular key. If the map does not already contain such an object,
operator[]
inserts the default objectdata_type()
.
(The SGI STL documentation is not documentation for the C++ Standard Library, but it is still an invaluable resource as most of the behavior of the Standard Library containers is the same or very close to the behavior of the SGI STL containers.)
Why does some_dict['key'] = somevalue work if the key is not in some_dict?
The operations:
some_dict[key]
and
some_dict[key] = value
and
del some_dict[key]
use different special methods of the object: __getitem__
, __setitem__
and __delitem__
. So it's not just one operator ([]
) that implements them all.
Maybe an example can illustrate that:
class Something(dict): # subclassing dict
def __getitem__(self, key):
print('trying to get', key)
return super().__getitem__(key)
def __setitem__(self, key, value):
print('trying to set', key, 'to', value)
return super().__setitem__(key, value)
def __delitem__(self, key):
print('trying to delete', key)
return super().__delitem__(key)
Test:
>>> s = Something({'a': 1, 'b': 2})
>>> s['a']
trying to get a
1
>>> s['c'] = 10
trying to set c to 10
>>> del s['b']
trying to delete b
So it depends on how they are implemented. In plain Python dict
s __getitem__
just returns the value for the key or throws if it's not present.
But subclasses could also implement the __missing__
method - in case they want to customize the behavior if the key wasn't present in the dict (during lookup).
How to check if a map contains a key in Go?
One line answer:
if val, ok := dict["foo"]; ok {
//do something here
}
Explanation:
if
statements in Go can include both a condition and an initialization statement. The example above uses both:
initializes two variables -
val
will receive either the value of "foo" from the map or a "zero value" (in this case the empty string) andok
will receive a bool that will be set totrue
if "foo" was actually present in the mapevaluates
ok
, which will betrue
if "foo" was in the map
If "foo" is indeed present in the map, the body of the if
statement will be executed and val
will be local to that scope.
Determine if map contains a value for a key?
Does something along these lines exist?
No. With the stl map class, you use ::find()
to search the map, and compare the returned iterator to std::map::end()
so
map<int,Bar>::iterator it = m.find('2');
Bar b3;
if(it != m.end())
{
//element found;
b3 = it->second;
}
Obviously you can write your own getValue()
routine if you want (also in C++, there is no reason to use out
), but I would suspect that once you get the hang of using std::map::find()
you won't want to waste your time.
Also your code is slightly wrong:
m.find('2');
will search the map for a keyvalue that is '2'
. IIRC the C++ compiler will implicitly convert '2' to an int, which results in the numeric value for the ASCII code for '2' which is not what you want.
Since your keytype in this example is int
you want to search like this: m.find(2);
Value given by map when key does not exsist
A new default key is constructed having the value
' '
.
No, that's wrong. The "default" value for a char
is 0
, as for any other integer numeric type.
Is there any documentation for the same?
The behavior of the std::map::operator[]
is documented in detail here.
Key existence check in HashMap
Do you ever store a null value? If not, you can just do:
Foo value = map.get(key);
if (value != null) {
...
} else {
// No such key
}
Otherwise, you could just check for existence if you get a null value returned:
Foo value = map.get(key);
if (value != null) {
...
} else {
// Key might be present...
if (map.containsKey(key)) {
// Okay, there's a key but the value is null
} else {
// Definitely no such key
}
}
Checking if key exists in Presto value map
You can lookup a value in a map
if the key is present with element_at
, like this:
SELECT element_at(value_map, 'element')
FROM ...
WHERE element_at(value_map, 'element') IS NOT NULL
Related Topics
Matlab VS C++ Double Precision
Vector::At VS. Vector::Operator[]
Is a Destructor Called When an Object Goes Out of Scope
Is Destructor Called If Sigint or Sigstp Issued
Compiling with -Static-Libgcc -Static-Libstdc++ Still Results in Dynamic Dependency on Libc.So
Why Does Clang Optimize Away X * 1.0 But Not X + 0.0
How to Store a 64 Bit Integer in Two 32 Bit Integers and Convert Back Again
Why Is Partial Specialization of a Nested Class Template Allowed, While Complete Isn'T
Error: Member Access into Incomplete Type:Forward Declaration Of
Why Is a Char and a Bool the Same Size in C++
Does Constraint Subsumption Only Apply to Concepts
When Do Compilers Inline C++ Code
Setting the Cursor Position in a Win32 Console Application
Enumerating All Available Drive Letters in Windows