Searching a list

Hi, I made a Double Linked List data structure. But I am in a snag for a certain part of my program. I have a player class, with name,age,exp. I can add players to my list and stuff ok.

My problem is this:
I want to search my list based on one of those fields. For instance, I want to search each players exp field, and see if it matches a certain number. But, I am stumped how I can do this. My custom list is a tenplate class. So, How can I iterate through the list and pick out only the players that have exp at say 100?
I call the search using list.Search(some params) from my main method.


Ok, I have made some progress, I set the return value of the search method to be of Datatype. Therefore, it will return a player object. I then test the values in my main. Is there a better way of doing this?
Last edited on
Use a predicate class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class PlayerPredicate
{
private:
bool checkExp, checkHp;
int expCheckValue, hpCheckValue;
public:
PlayerPredicate() : checkExp(false), checkHp(false),
                              expCheckValue(0), hpCheckValue(0)
{}
void addExpCheck(int exp)
{
     checkExp = true;
     expCheckValue = exp;
}
void addHpCheck(int hp)
{
     checkHp = true;
     hpCheckValue = hp;
}
bool operator()(const Player& player)
{
     if(checkExp)
         if(player.exp()!=expCheckValue)
         return false;
     if(checkHp)
        if(player.hp()!=hpCheckValue)
        return false;
     return true;
}
};


Then you use this as a predicate when iterating over the list:
1
2
3
4
//stuff
if(predicate(player))
return player;
//stuff 


Along those lines.
I just did it the way I thought of(simplest way), I have the Search function returning the Datatype, and I pass into the function a reference to the iterator. Then I do the checks inside my main.cpp.

Thanks for your help anyway.
Topic archived. No new replies allowed.