Existence of a key in std::map

How can I check if a particular key exists in a std::map or not?

Here’s what I know,

   if(m.count(key)==0)     ///// m is a std::map
        key does not exist
   else if(m.count(key)>=0)
        key exists

Is it correct?

What does “count” do?

Any better way?

Here is link where your doubt will be cleared…

1 Like

Try this

if(m.find(key) == m.end()) { // key doesnt exist
    // todo code
} else { // key exists
    // todo code
    // use m.find(key)->second to print value
1 Like

Is it possible to get m.count(key)>1 ?

As all elements in a map container are unique, the function can only return 1 (if the element is found) or 0. SO it will not return ay number greater than 1. Ok

Thanks @bansal1232!

1 Like