Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectors, structs and std::find

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 !

like image 757
Ahmed Avatar asked Feb 26 '09 10:02

Ahmed


People also ask

Is there a find in vector C++?

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.

What does std :: find do?

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 .

How do you check if an element exists in a vector?

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.


1 Answers

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)); 
like image 82
Johannes Schaub - litb Avatar answered Sep 28 '22 11:09

Johannes Schaub - litb