SomethingSomething
SomethingSomething

Reputation: 12266

C++ - how to tell whether a key exists in map of maps

I have the following structure:

std::map<int, std::map<int, int>> my_map;

I want to check whether the key my_map[3][5] exists.

Is there any easier/shorter way to do so except for something like:

if (my_map.find(3) != my_map.end()) {
    std::map<int, int>& internal_map = my_map[3];
    if (internal_map.find(5) != internal_map.end()) {
        // ... Do something ...
    }
}

Upvotes: 2

Views: 964

Answers (2)

Angel Angel
Angel Angel

Reputation: 21748

You could use this:

int k  = 3;
int k1 = 5;

std::map<int, int>::iterator it = my_map[k].end();

if( (my_map.find(k))->second.find(k1) != it ){
    std::cout << "something";
}

Upvotes: 0

Martin Perry
Martin Perry

Reputation: 9527

You could improve it a little via:

std::map<int, std::map<int, int>>::iterator it = my_map.find(3);
if (it != my_map.end()){
    if (it->second.find(5) != internal_map.end()) {
    }
}

In your current solution, you are finding the key twice and it could be slower than finding it once and store it in iterator.

Upvotes: 5

Related Questions