看看c++中是否有一个键

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

本文关键字:有一个 是否 c++ 看看      更新时间:2023-10-16

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

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?

是检查键是否存在的正确方法吗?

是的,这是正确的方法。键对应的值存储在std::map迭代器的second成员中。

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
}

无需遍历所有项,只需访问具有指定键的项。

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
}
相关文章: