c++ - vector 、结构和 std::find

标签 c++ data-structures find vector

我还是用 vector 。我希望我不会太烦人。我有一个这样的结构:

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

所以我创建了一个 vector :

std::vector<monster> monsters;

但现在我不知道如何通过 vector 进行搜索。我想在 vector 中找到怪物的 ID。

DWORD monster = 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));

关于c++ - vector 、结构和 std::find,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31052249/

相关文章:

c++ - "using std::swap"如何启用ADL?

c# - C# 中的多键字典(另一种)?

c - 出现段错误。不知道为什么

c++ - 将 SIGTERM 绑定(bind)到成员函数

c++ - 有没有办法禁用非动态类构造函数?

c++ - 在 C++ 中构造一个 'is_template_instantiable' 类型特征

java - 我需要实现一个数组哈希表,该表无需在开始时将数组初始化为 null 即可工作。任何线索如何做到这一点?

arrays - 是否有可能在 O(n) 时间内找到给定数组中的所有三元组?

linux - 查找在一个小时内修改另一个文件的文件

collections - 在数组列表中收集 findall