2016-04-30 47 views
0

我的目標是查找Key(objName)(如果存在),然後返回該值。使用map :: find查找密鑰並返回值

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 

我不明白什麼問題。提前致謝!

+2

無關你的問題見http://en.cppreference.com/w/cpp/container/map/find,我想你的意思'contents.find(OBJNAME)= contents.end()'.. 。 –

回答

3

沒有必要爲一個循環爲find返回一個迭代器找到的元素或end()在不匹配的情況下。

因此,所有你需要的是:

map<string, GameEntity*>:: iterator iter = contents.find(objName); 
if(iter != contents.end()) // notice the != 
    return (iter->second); 
else 
    return NULL; 

的細節

+0

運行程序後,它仍然跳轉到上面的錯誤。這是否意味着我的代碼中有其他地方存在錯誤。它打開一個stl_pair.h文件... – Ares

+0

@Ares可能是。 –

+0

@Ares - 是的,我也覺得你在另一個地方有問題。有關搜索代碼的運行示例,請參閱https://ideone.com/9M2Kny – 4386427

0

爲什麼在世界上你使用for循環?

試試這個:

decltype(auto) iter = contents.find(objName); 
return iter != contents.end() ? iter : nullptr; 

(注:NULL宏已被棄用,使用nullptr代替。)

+0

'decltype(auto)'?你的意思是隻使用'auto'嗎? –

+0

@RSahu nope,我更喜歡'decltype(auto)',因爲它提供的引用類型'auto'不會。 (在這種情況下,我相信它會給'decltype(contents):: iterator &&',wheras'auto'會給出'decltype(contents):: iterator')。 (注意:我可能是錯的,我目前無法訪問編譯器...來測試它) – Isaac

+0

'decltype(auto)'是錯誤的。 「decltype」的參數需要是一個表達式。 –