Vectors,structs和std :: find [英] Vectors, structs and std::find

查看:92
本文介绍了Vectors,structs和std :: find的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

再次,我用向量。我希望我不是太烦人了我有一个这样的结构:

  struct monster 
{
DWORD id;
int x;
int y;
int distance;
int HP;
};

所以我创建了一个向量:

  std :: vector< monster>怪物

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

  DWORD怪物= 0xFFFAAA; 
it = std :: find(bot.monsters.begin(),bot.monsters.end(),currentMonster);

但显然它不起作用。我只想通过结构体的.id元素进行迭代,我不知道该怎么做。帮助非常感谢。谢谢!

解决方案

std :: find_if

  it = std :: find_if(bot.monsters.begin(),bot.monsters.end(),
boost :: bind(& monster :: id,_1)== currentMonster);

或者如果没有boost,则编写自己的函数对象。看起来像这样

  struct find_id:std :: unary_function< monster,bool> {
DWORD id;
find_id(DWORD id):id(id){}
bool operator()(monster const& m)const {
return m.id == id;
}
};

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


Again me with vectors. I hope I'm not too annoying. I have a struct like this :

struct monster 
{
    DWORD id;
    int x;
    int y;
    int distance;
    int HP;
};

So I created a vector :

std::vector<monster> monsters;

But now I don't know how to search through the vector. I want to find an ID of the monster inside the vector.

DWORD monster = 0xFFFAAA;
it = std::find(bot.monsters.begin(), bot.monsters.end(), currentMonster);

But obviously it doesn't work. I want to iterate only through the .id element of the struct, and I don't know how to do that. Help is greatly appreciated. Thanks !

解决方案

std::find_if:

it = std::find_if(bot.monsters.begin(), bot.monsters.end(), 
        boost::bind(&monster::id, _1) == currentMonster);

Or write your own function object if you don't have boost. Would look like this

struct find_id : std::unary_function<monster, bool> {
    DWORD id;
    find_id(DWORD id):id(id) { }
    bool operator()(monster const& m) const {
        return m.id == id;
    }
};

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

这篇关于Vectors,structs和std :: find的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆