【问题标题】:see if there is a key in a map c++查看地图c ++中是否有键
【发布时间】:2011-12-13 02:32:13
【问题描述】:

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

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?

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

【问题讨论】:

  • @FailedDev 我不同意建议的重复项-该问题是关于搜索 values 但这个问题是关于搜索 keys (然后使用相应的值,但它们是非常不同的问题)

标签: c++ map find key


【解决方案1】:

是的,这是正确的方法。与键关联的值存储在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
}

【讨论】:

    【解决方案2】:

    无需遍历所有项,只需使用指定键访问一项即可。

    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
    }
    

    【讨论】:

    • 也不需要查找该项目两次。 find() 返回一个迭代器直接访问它。
    • 不要那样做。您现在正在搜索树两次。该值在 find(key)->second 中可用(假设它不是 end)。
    • 我知道,这只是为了可读性和展示 [] 运算符的用法。将编辑我的答案。
    • @LuchianGrigore 仍然错误(或不合适),因为 *it 返回一个键值对。直接使用it-&gt;second 可以更轻松地检索实际值。你有没有看过 5 分更好的答案,或者至少是你的 cmets?
    猜你喜欢
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多