3

Possible Duplicate:
How to find if a given key exists in a C++ std::map

In C++, how can I check if there is an element with a key?

jww
  • 97,681
  • 90
  • 411
  • 885
Safari
  • 11,437
  • 24
  • 91
  • 191

2 Answers2

9
if (myMap.find(key) != myMap.end())
{ // there is such an element
}

See the reference for std::map::find

Benoit
  • 76,634
  • 23
  • 210
  • 236
8

Try to find it using the find method, which will return the end() iterator of your map if the element is not found:

if (data.find(key) != data.end()) {
    // key is found
} else {
    // key is not found
}

Of course you shouldn't find twice if you need the value corresponding to the given key later. In this case, simply store the result of find first:

YourMapType data;
...
YourMapType::const_iterator it;
it = data.find(key);
if (it != data.end()) {
    // do whatever you want
}
Tamás
  • 47,239
  • 12
  • 105
  • 124