c++ - 使用 map::find 查找键并返回值

标签 c++ for-loop dictionary iterator find

我的目标是寻找一个 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

我不明白这是怎么回事。提前致谢!

最佳答案

不需要循环,因为 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详情

关于c++ - 使用 map::find 查找键并返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951133/

相关文章:

c++ - 如何为类中的模板定义类型别名

c++ - 如何设置水平标题QHeaderView的高度?

variables - 使用 Xpath for..in..return 时在 XSLT/XPath 中创建增量计数变量?

python - 将字典中的列表作为新列添加到 DataFrame

python - 有没有一种 pythonic 的方法来获取字典中列表中的变量总数?

python使用列表理解对dict的多级列表进行切片

c++ - 获取指向对象成员函数的指针

c++ - 获取应用程序 Windows 的完整目录

c++ - 用C++添加整数

r - 在 R markdown 文档中循环生成可格式化的小部件