Alfred Zhong
Alfred Zhong

Reputation: 7081

unordered_map judge if the key is in the map

I tried this piece of code

 #include <iostream>
 #include <utility>
 #include <vector>
 #include <unordered_map>
 #include <stdexcept>

 using namespace std;

 int main() {
    unordered_map<int,int> parent_map;
    try {
        int a = parent_map[0];
        cout<<a<<endl;

    } catch (out_of_range oe) {
        cout<<"out of range"<<endl;
    }

    return 0;

 }

I think the out of range exception should be caught. However, the output is

0

I am confused. I remember I got this working before.

Upvotes: 0

Views: 649

Answers (2)

billz
billz

Reputation: 45410

operator[] doesn't throw, you want to try std::unordered_map::at

int a = parent_map.at(0);

Also operator[] will insert an element if key is not found.

And you want to capture exception by reference

catch (const out_of_range &oe) {
   cout<<"out of range: " << oe.what() <<endl;
}

Upvotes: 5

Aesthete
Aesthete

Reputation: 18850

int a = parent_map[0];

Is assigning a new entry to the map with key 0, and default value 0.

You're essentially doing this:

parent_map[0] = int();

What you want to do is find() the key in the map, and check it's not the end of the container.

if(parent_map.find(0) != parent_map.end())
{
  // Element exists.
}

Upvotes: 1

Related Questions