查看地图中是否有密钥c ++

时间:2011-10-22 09:45:19

标签: c++ map find key

在我的函数中,我有这个参数:

map<string,int> *&itemList

我想首先检查一个密钥是否存在。如果此键存在,则获取该值。 我想这个:

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?

是检查密钥是否存在的正确方法?

2 个答案:

答案 0 :(得分:6)

是的,这是正确的方法。与密钥关联的值存储在second迭代器的std::map成员中。

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
}

答案 1 :(得分:1)

无需遍历所有项目,只需访问具有指定密钥的项目即可。

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

编辑:

之前的版本会两次查找地图。更好的解决方案是:

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