Safari
Safari

Reputation: 11965

see if there is a key in a map c++

in my function, i have this parameter:

map<string,int> *&itemList

I want to first check if a key exists. If this key exists obtain the value. I thought this:

map<string,int>::const_iterator it = itemList->find(buf.c_str());
if(it!=itemList->end())
    //how can I get the value corresponding to the key?

is the correct way to check whether the key exists?

Upvotes: 3

Views: 1761

Answers (2)

Luchian Grigore
Luchian Grigore

Reputation: 258638

No need to iterate through all the items, you can just access the one with the specified key.

if ( itemList->find(key) != itemList->end() )
{
   //key is present
   return *itemList[key];  //return value
}
else
{
   //key not present
}

EDIT:

The previous version looks up the map twice. A better solution would be:

map::iterator<T> it = itemList->find(key);
if ( it != itemList->end() )
{
   //key is present
   return *it;  //return value
}
else
{
   //key not present
}

Upvotes: 1

ks1322
ks1322

Reputation: 35825

Yes, this is correct way to do this. The value associated with the key is stored in second member of std::map iterator.

map<string,int>::const_iterator it = itemList->find(buf.c_str());
if(it!=itemList->end())
{
  return it->second; // do something with value corresponding to the key
}

Upvotes: 6

Related Questions