Daniel
Daniel

Reputation: 7724

What does unordered_map returns when looking for a key that doesn't exist

I have an unordered_map<char, mystruct> h.

What does this return if h doesn't contain a key x?

mystruct ms = h['x'];

Upvotes: 1

Views: 5250

Answers (3)

Edwin Chew
Edwin Chew

Reputation: 49

The unordered map will try to default initialize mystruct with the key 'x' and assign to mystruct.

If you desire to avoid this, use .at(key). If it doesn't exist, it will throw an out_of_range exception which you can catch and handle.

Upvotes: 2

Aayush Choubey
Aayush Choubey

Reputation: 1

if you directly use h['any key which is not present'] then it will give it some random value. what you can do is whenever you're not sure about whether it is there or not just use it inside an if. if it is present it will return true and if not then false. example: if(h['a'])cout<<h['a'];

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 173044

If the specified key 'x' doesn't exist, std::unordered_map::operator[] will insert a value-initialized mystruct firstly, then return the reference to the inserted mystruct. After that ms is copy-initialized from the inserted mystruct.

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

When the default allocator is used, this results in ... the mapped value being value-initialized.

Return value
Reference to the mapped value of the new element if no element with key key existed.

Upvotes: 6

Related Questions