Determine if map contains a value for a key?

What is the best way to determine if a STL map contains a value for a given key?

#include <map>

using namespace std;

struct Bar
{
    int i;
};

int main()
{
    map<int, Bar> m;
    Bar b = {0};
    Bar b1 = {1};

    m[0] = b;
    m[1] = b1;

    //Bar b2 = m[2];
    map<int, Bar>::iterator iter = m.find(2);
    Bar b3 = iter->second;

}

Examining this in a debugger, it looks like iter is just garbage data.

If I uncomment out this line:

Bar b2 = m[2]

The debugger shows that b2 is {i = 0}. (I’m guessing it means that using an undefined index will return a struct with all empty/uninitialized values?)

Neither of these methods is so great. What I’d really like is an interface like this:

bool getValue(int key, Bar& out)
{
    if (map contains value for key)
    {
        out = map[key];
        return true;
    }
    return false;
}

Does something along these lines exist?

11 Answers
11

Leave a Comment