Determine if map contains a value for a key?

Nick Heiner picture Nick Heiner · Jun 29, 2010 · Viewed 382.4k times · Source

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?

Answer

pconnell picture pconnell · Aug 1, 2012

As long as the map is not a multimap, one of the most elegant ways would be to use the count method

if (m.count(key))
    // key exists

The count would be 1 if the element is indeed present in the map.