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?
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?
if (myMap.find(key) != myMap.end())
{ // there is such an element
}
See the reference for std::map::find
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
}