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?
No. With the stl map class, you use
::find()to search the map, and compare the returned iterator tostd::map::end()so
Obviously you can write your own
getValue()routine if you want (also in C++, there is no reason to useout), but I would suspect that once you get the hang of usingstd::map::find()you won’t want to waste your time.Also your code is slightly wrong:
m.find('2');will search the map for a keyvalue that is'2'. IIRC the C++ compiler will implicitly convert ‘2’ to an int, which results in the numeric value for the ASCII code for ‘2’ which is not what you want.Since your keytype in this example is
intyou want to search like this:m.find(2);