3

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?

Safari
  • 11,437
  • 24
  • 91
  • 191
  • 1
    Possible duplicate of : http://stackoverflow.com/questions/535317/checking-value-exist-in-a-stdmap-c – FailedDev Oct 22 '11 at 09:47
  • @FailedDev I disagree with the proposed duplicate - that question is asking about searching for *values* but this question is about searching for *keys* (and then using the corresponding value, but they're very different questions) – Flexo Oct 23 '11 at 13:47

2 Answers2

6

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
}
ks1322
  • 33,961
  • 14
  • 109
  • 164
1

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
}
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 1
    No need to look up the item twice, either. `find()` returns an iterator to access it directly. – Mike Seymour Oct 22 '11 at 10:24
  • 1
    Don't do that. You are now searching the tree twice. The value is available in find(key)->second (assuming it is not end). – Martin York Oct 22 '11 at 10:25
  • I knew that, it was just for readability and to show the usage of the [] operator. Will edit my answer. – Luchian Grigore Oct 22 '11 at 10:43
  • 1
    @LuchianGrigore Still wrong (or unappropriate), as `*it` returns a key-value pair. The actual value can be retrieved more easily using `it->second` directly. Have you even looked at the 5 points better answer or at least the comments to yours? – Christian Rau Oct 22 '11 at 16:48