[英]What kind of value will map::find() return if “key” does'nt exist?
[英]Using map::find to find a key and return the value
我的目標是尋找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
您為什么在世界上使用for循環?
嘗試這個:
decltype(auto) iter = contents.find(objName);
return iter != contents.end() ? iter : nullptr;
(注意:不建議使用NULL
宏,請改用nullptr
。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.