我的目标是寻找一个 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;
关于c++ - 使用 map::find 查找键并返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951133/