私が見る限り、内側と外側のラムダでも「名前」をキャプチャする必要があります。
一方、エンティティは関数の引数であるため、キャプチャしてはなりません。
また、を使用することはお勧めしませんstd::list<Entity*>>
。一部のコンパイラは前者をoperator<およびoperator>>と誤解するため、
むしろ使用してください。std::list<Entity*> >
コンパイルするようにコードを修正しました:(string & name
参照によってキャプチャされます)
Entity *Engine::findEntity(const std::string &name)
{
using namespace std;
for_each(p_entities.begin(), p_entities.end(),
[&name](pair<const int, const list<Entity*>>& pair)
{
for_each((pair.second).begin(),(pair.second).end(),
[&name](const Entity* entity)
{
if ( entity->getAlive() == true && entity->getName() == name )
return entity;
});
});
return nullptr;
}
このコードを再確認しますが、問題はないはずです。(さらにいくつかの&を置き忘れた場合を除いて、ペアはconst refである必要があり、entityは単なるconstポインターである必要があります。)
提案:コードをもう少し読みやすくするために、ラムダヘッダーを次の行に分割し、関数内で使用することもできますusing namespace std
。
更新:コードにはまだバグがあります。return
ラムダからのみ返されますが、見つかったエンティティは返されません。
UPDATE2:関数が正しく実行されるようにさらに修正します。
// returns the last found entity.
const Entity *Engine::findEntity(const std::string &name)
{
using namespace std;
const Entity * found_entity=nullptr;
for_each(p_entities.begin(), p_entities.end(),
[&name, &found_entity](pair<const int, const list<Entity*> >& pair)
{
for_each((pair.second).begin(),(pair.second).end(),
[&name, &found_entity](const Entity* entity)
{
if( entity->getAlive() == true && entity->getName() == name )
found_entity = entity; // here you need to modify the variable captured from the outside.
});
});
return found_entity;
}
for_each
ただし、この場合は使用しませんbreak
。エンティティが検出された後でもループを終了する必要があるためです。ここではイテレータを使用したいと思います。
この部分はOP専用です。これは私が空白を埋めた方法です(コード全体):
#include <iostream>
#include <list>
#include <string>
#include <map>
#include <algorithm>
class Entity{
public:
bool getAlive() const {return true;}
std::string getName() const {return "Barna";}
};
class Engine{
public:
const Entity *findEntity(const std::string& name);
private:
std::map<int, const std::list<Entity*> > p_entities;
};
const Entity *Engine::findEntity(const std::string &name)
{
using namespace std;
const Entity* found_entity = nullptr;
for_each(p_entities.begin(), p_entities.end(),
[&name, &found_entity](pair<const int, const list<Entity*> >& pair)
{
for_each((pair.second).begin(),(pair.second).end(),
[&name, &found_entity](const Entity* entity)
{
if ( entity->getAlive() == true && entity->getName() == name )
found_entity = entity;
});
});
return found_entity;
}
int main()
{
Engine e;
e.findEntity("he");
}