簡體   English   中英

使用map :: find找到一個鍵並返回值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM