43

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 !

1
  • 1
    Great question, exactly what I needed. Not annoying at all:)
    – tomereli
    Apr 5, 2018 at 8:03

7 Answers 7

42

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));
9
  • 1
    using boost, Perfect!
    – H'H
    Nov 14, 2014 at 16:05
  • 2
    What is the meaning of "bot" in bot.monsters.begin()? Jan 7, 2016 at 10:54
  • 3
    What is the datatype if "it"??
    – nathan
    Oct 14, 2016 at 17:35
  • 1
    good thing you gave an example without boost - we never use boost in embedded systems, it is huge. I just didn't understand why you inherited the functor object from std::unary_function - looks like it would work either way, won't it? appreciate your answer.
    – tomereli
    Apr 5, 2018 at 7:50
  • 1
    @Hiyper - The type would be std::vector<monster>::iterator. Or you can use auto it = std::find_if... if you are using c++11
    – tomereli
    Apr 5, 2018 at 8:02
26

how about:

std::find_if(monsters.begin(), 
             monsters.end(), 
             [&cm = currentMonster]
             (const monster& m) -> bool { return cm == m; }); 
5
  • 2
    Could someone who sees this walk me through what it's doing? Specifically the [&cm = currentMonster](const monster& m) -> bool { return cm == m; });
    – 2kreate
    Nov 29, 2014 at 19:57
  • 7
    This example uses a lambda function, which depends on C++11. [&cm = currentMonster] binds the variable currentMonster from the calling scope to a local reference in the lambda, called cm. Then (const monster& m) -> bool defines the signature of the lambda, taking one input parameter, m, and returning bool. The body of the lambda function is { return cm == m; }, returning true if cm and m compare as equal. Jun 25, 2015 at 13:56
  • 1
    Finally I know how to properly bind local variables to lambdas. Oct 20, 2015 at 14:43
  • is the -> bool part necessary? it would compile either way, won't it?
    – tomereli
    Apr 5, 2018 at 8:24
  • 1
    The { return cm == m; } at the end requires an operator== defined in the struct (see @dirkgently answer), Without the operator==, change the return statement to { return cm.id == m.id; } Mar 27, 2019 at 1:18
21

You need to write your own search predicate:

struct find_monster
{
    DWORD id;
    find_monster(DWORD id) : id(id) {}
    bool operator () ( const monster& m ) const
    {
        return m.id == id;
    }
};

it = std::find_if( monsters.begin(), monsters.end(), find_monster(monsterID));
2
  • Nice answer, but there is a typo in the constructor. It should be ':' not ';' Aug 24, 2012 at 15:16
  • In addition to writing your own search predicate, you need to use std::find_if instead of std::find. Aug 25, 2012 at 16:34
9

Take a look at the std::find template, the third parameter especially:

template<class InputIterator, class EqualityComparable>
InputIterator find(InputIterator first, InputIterator last,
               const EqualityComparable& value);

What is this EqualityComparable? Again from the documentation:

A type is EqualityComparable if objects of that type can be 
compared for equality using operator==, and if operator== is 
an equivalence relation. 

Now, your type monster needs to define such an operator. If you don't the compiler generates one for you (as also the default ctor and the dtor) which does a memcmp sort of thing which doesn't work in your case. So, to use std::find first define a comparator function/functor that the algorithm can use to match your currentMonster i.e. something along the lines of:

 struct monster {
  // members
  bool operator==(const monster& l, const monster& r) const
  {
     return l.id == r.id;
  }
 };
3
  • 7
    Does this work? I did not have success because an operator definition inside a struct can only have 1 input Apr 15, 2013 at 8:20
  • Same problem as Snoozer. -1, please complete the answer. Oct 20, 2015 at 14:42
  • 2
    the concept is correct. this works for me: bool operator==(const monster& r) const { return id == r.id; } Mar 27, 2019 at 0:54
1

or put the monsters in a map instead of a vector

or if they must be in a vector create an index map ie map of ID to vector index

0

This is a complete sample based on the answer of Johannes Schaub (boost version).

#include <algorithm>
#include <boost/bind.hpp>

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

int main ()
{
    std::vector<monster> monsters;

    monster newMonster;
    newMonster.id    = 1;
    newMonster.x     = 10;
    monsters.push_back ( newMonster );

    newMonster.id    = 2;
    newMonster.x     = 20;
    monsters.push_back ( newMonster );

    newMonster.id    = 2;
    newMonster.x     = 30;
    monsters.push_back ( newMonster );

    DWORD monsterId = 2;

    std::vector< monster >::iterator it = std::find_if ( monsters.begin (), monsters.end (), 
        boost::bind ( &monster::id, _1 ) == monsterId );

    return 0;
}
0

You can write a function as below:

monster* findMonster(DWORD currentMonster) {
    for (auto it = bot.monsters.begin(); it != bot.monsters.end(); it++) {
        if (it->id == currentMonster) {
            return &(*it);
        }
    }
    return NULL;
}

It returns a pointer to the stored node if it's found in the vector, otherwise returns NULL.

Please note that return it; won't work directly.

1
  • How are you even compiling this? It fails on latest C++ and VS2019.
    – Mecanik
    Mar 5, 2022 at 5:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.