2016-04-30 4 views
0

私の目標は、存在する場合はキー(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

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

を(NULLマクロが廃止され、代わりにnullptrを使用します)。一致しない場合は

だから、あなたが必要とするすべては、次のとおりです!

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

@おそらくあります。 –

+0

@Ares - はい、私はまたあなたが別の場所に問題があると思います。検索コードの実行例については、https://ideone.com/9M2Knyを参照してください。 – 4386427

0

なぜforループを使用していますか?

この試し:findが見つかった要素又はend()にイテレータを返すようにループの必要はありません

+0

'decltype(auto)'? 'auto'だけを使うのですか? –

+0

@RSahuいいえ、私は 'auto'が参照しない型を与えるので、' decltype(auto) 'を好きです。 (この場合、 'decltype(contents):: iterator &&'を与え、 'auto'は' decltype(contents):: iterator'を与えると信じています)。 (注:私は間違っているかもしれませんが、私は現在、コンパイラへのアクセス権がありません...テストするために) – Isaac

+0

'decltype(auto)'が間違っています。 'decltype'への引数は式でなければなりません。 –

関連する問題