向量,结构和std :: find

再次给我带来了载体。我希望我不会太烦人。我有一个这样的结构:


struct monster 

{

    DWORD id;

    int x;

    int y;

    int distance;

    int HP;

};

所以我创建了一个向量:


std::vector<monster> monsters;

但是现在我不知道如何搜索向量。我想在向量中找到怪物的ID。


DWORD monster = 0xFFFAAA;

it = std::find(bot.monsters.begin(), bot.monsters.end(), currentMonster);

但是显然这是行不通的。我只想遍历该结构的.id元素,但我不知道该怎么做。非常感谢您的帮助。谢谢 !


阿波罗的战车
浏览 525回答 3
3回答

慕婉清6462132

std::find_if:it = std::find_if(bot.monsters.begin(), bot.monsters.end(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; boost::bind(&monster::id, _1) == currentMonster);或编写没有增强功能的函数对象。看起来像这样struct find_id : std::unary_function<monster, bool> {&nbsp; &nbsp; DWORD id;&nbsp; &nbsp; find_id(DWORD id):id(id) { }&nbsp; &nbsp; bool operator()(monster const& m) const {&nbsp; &nbsp; &nbsp; &nbsp; return m.id == id;&nbsp; &nbsp; }};it = std::find_if(bot.monsters.begin(), bot.monsters.end(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;find_id(currentMonster));

隔江千里

怎么样:std::find_if(monsters.begin(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;monsters.end(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[&cm = currentMonster]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(const monster& m) -> bool { return cm == m; });&nbsp;

忽然笑

您需要编写自己的搜索谓词:struct find_monster{&nbsp; &nbsp; DWORD id;&nbsp; &nbsp; find_monster(DWORD id) : id(id) {}&nbsp; &nbsp; bool operator () ( const monster& m ) const&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return m.id == id;&nbsp; &nbsp; }};it = std::find_if( monsters.begin(), monsters.end(), find_monster(monsterID));
打开App,查看更多内容
随时随地看视频慕课网APP