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?

3
  • @Space_C0wb0y: Hardly. Learn the difference between a key and a value. Commented May 6, 2011 at 13:36
  • Actually, the title of that question is misleading, it is indeed about finding whether a given key exists in a std::map. Commented May 6, 2011 at 13:38
  • @Tomalak: Upon rereading the question and all answers, I am reasonably sure that it is a duplicate. Although the title is inaccurate. Commented May 6, 2011 at 13:39

2 Answers 2

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

See the reference for std::map::find

Sign up to request clarification or add additional context in comments.

5 Comments

+1 (though I wouldn't recommend cplusplus.com to language newcomers).
@Tomalak Geret'kal: are you sure that OP is a newcomer? And what would you recommend instead?
I am curious , what is so bad about cplusplus? I use it quite often to understand small bits.
The question rather gives it away.
@RickoM: cplusplus.com is notoriously error-ridden, and its tutorials are misleading (even for tutorials). I use it myself as a "reminder" reference, but I know C++ well enough to spot the mistakes, and absolutely would not recommend it.
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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.