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 !
You can use the find function, found in the std namespace, ie std::find . You pass the std::find function the begin and end iterator from the vector you want to search, along with the element you're looking for and compare the resulting iterator to the end of the vector to see if they match or not.
std::find. Returns an iterator to the first element in the range [first,last) that compares equal to val . If no such element is found, the function returns last .
So, to check if an element exist in vector or not, we can pass the start & end iterators of vector as initial two arguments and as the third argument pass the value that we need to check. If element exists in the vector, then it will return the iterator pointing to that element.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With