C++ 使用map::find查找键并返回值
我的目标是寻找一个键(objName)(如果它存在),然后返回值C++ 使用map::find查找键并返回值,c++,for-loop,dictionary,iterator,find,C++,For Loop,Dictionary,Iterator,Find,我的目标是寻找一个键(objName)(如果它存在),然后返回值 GameEntity * GameEntity::FindInContents(string objName) { for( map<string, GameEntity*>:: iterator iter = contents.begin(); iter != contents.end(); iter++) { if(contents.find(objName)== contents.en
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;
}
}
GameEntity*GameEntity::FindInContents(字符串objName)
{
for(map::iterator iter=contents.begin();iter!=contents.end();iter++)
{
if(contents.find(objName)=contents.end())
返回(iter->秒);
其他的
返回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
/**@c pair类本身也有一个模板化的复制构造函数*/
#ifndef\uuuugxx\uCxx0x__
模板
对(常数对和常数对)
:第一(u p.first),第二(u p.second){
#否则
我不明白是什么问题。提前谢谢 你到底为什么要使用for循环 试试这个:
decltype(auto) iter = contents.find(objName);
return iter != contents.end() ? iter : nullptr;
(注意:
NULL
宏已被弃用,请改用nullptr
。为什么要使用for循环
试试这个:
decltype(auto) iter = contents.find(objName);
return iter != contents.end() ? iter : nullptr;
(注意:不推荐使用
NULL
宏,请改用nullptr
。不需要循环,因为find
会向找到的元素返回迭代器,或者在不匹配的情况下返回end()
因此,您所需要的是:
map<string, GameEntity*>:: iterator iter = contents.find(objName);
if(iter != contents.end()) // notice the !=
return (iter->second);
else
return NULL;
map::iterator iter=contents.find(objName);
if(iter!=contents.end())//注意=
返回(iter->秒);
其他的
返回NULL;
有关详细信息,请参见不需要循环,因为
find
将迭代器返回到找到的元素,或者在不匹配的情况下返回end()
因此,您所需要的是:
map<string, GameEntity*>:: iterator iter = contents.find(objName);
if(iter != contents.end()) // notice the !=
return (iter->second);
else
return NULL;
map::iterator iter=contents.find(objName);
if(iter!=contents.end())//注意=
返回(iter->秒);
其他的
返回NULL;
有关与您的问题无关的详细信息,请参见,我想您指的是
内容。查找(objName)!=contents.end()
…与您的问题无关,我想您的意思是contents.find(objName)!=contents.end()
…decltype(自动)
?你的意思是只使用auto
?@RSahu不,我更喜欢decltype(auto)
,因为它提供了auto
不会提供的引用类型。(在这种情况下,我相信它会给出decltype(contents)::iterator&
,而auto
会给出decltype(contents)::iterator
)。(注意:我可能错了,我目前没有访问编译器的权限…无法对其进行测试)decltype(auto)
错误。decltype
的参数必须是表达式。decltype(auto)
?你的意思是只使用auto
?@RSahu不,我更喜欢decltype(auto)
,因为它提供了auto
不会提供的引用类型。(在这种情况下,我相信它会给出decltype(contents)::iterator&
,而auto
会给出decltype(contents)::iterator
)。(注意:我可能错了,我目前没有访问编译器的权限…无法对其进行测试)decltype(auto)
错误。decltype
的参数需要是一个表达式。在我运行程序后,它仍然跳转到上面的错误。这是否意味着我的代码中的其他地方有错误。它打开了一个stl_pair.h文件…@Ares可能有。@Ares-是的,我想你在另一个地方也有问题。有关搜索代码的运行示例,请参阅。在我运行程序后,它仍然会跳转到上面的错误。这是否意味着我的代码中的其他地方有错误。它打开了一个stl_pair.h文件…@Ares可能有。@Ares-是的,我想你在另一个地方也有问题。有关搜索代码的运行示例,请参见