【问题标题】:Using map::find to find a key and return the value使用 map::find 查找键并返回值
【发布时间】:2016-08-25 08:53:06
【问题描述】:

我的目标是查找 Key(objName)(如果存在)然后返回值。

GameEntity * GameEntity::FindInContents(string objName)
{
   for( map<string, GameEntity*>:: iterator iter = contents.begin(); iter != contents.end(); iter++)
    {
       if(contents.find(objName)== contents.end())
           return (iter->second);
       else
           return NULL;
    }
}

但是当我运行代码时,它把我带到了

/** There is also a templated copy ctor for the @c pair class itself.  */
#ifndef __GXX_EXPERIMENTAL_CXX0X__
  template<class _U1, class _U2>
pair(const pair<_U1, _U2>& __p)
: first(__p.first), second(__p.second) { }
#else

我不明白这是什么问题。提前致谢!

【问题讨论】:

  • 与您的问题无关,我认为您的意思是contents.find(objName) != contents.end()...

标签: c++ for-loop dictionary iterator find


【解决方案1】:

不需要循环,因为find 将迭代器返回到找到的元素或end() 以防不匹配。

所以你只需要:

map<string, GameEntity*>:: iterator iter = contents.find(objName);
if(iter != contents.end())  // notice the !=
    return (iter->second);
else
    return NULL;

详情请见http://en.cppreference.com/w/cpp/container/map/find

【讨论】:

  • 运行程序后仍然跳转到上面的错误。这是否意味着我的代码中的其他地方存在错误。它会打开一个 stl_pair.h 文件...
  • @Ares 可能有。
  • @Ares - 是的,我也认为你在另一个地方有问题。搜索代码的运行示例见ideone.com/9M2Kny
【解决方案2】:

到底为什么要使用 for 循环?

试试这个:

decltype(auto) iter = contents.find(objName);
return iter != contents.end() ? iter : nullptr;

(注意:NULL 宏已弃用,请改用nullptr。)

【讨论】:

  • decltype(auto)?您的意思是只使用auto
  • @RSahu 不,我更喜欢decltype(auto),因为它提供了auto 不会提供的引用类型。 (在这种情况下,我相信它会给出decltype(contents)::iterator&amp;&amp;,而auto 会给出decltype(contents)::iterator)。 (注意:我可能错了,我目前无法访问编译器...对其进行测试)
  • decltype(auto) 是错误的。 decltype 的参数需要是一个表达式。
猜你喜欢
  • 2015-04-25
  • 1970-01-01
  • 2016-05-14
  • 1970-01-01
  • 2022-11-19
  • 2016-10-23
  • 2011-07-14
  • 2017-11-23
  • 2014-05-18
相关资源
最近更新 更多