gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:03:47 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com