Cycling through specific class names

Here's an example:
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

enum ItemEnum
{
     ITEM_ROCK,
     ITEM_STONE,
     ITEMNUM
};

class Item
{
public:
       string name;
       int id;
       
       void writename()
       {
            cout << name << " with ID " << id << " created." << endl;
       }
       
       int getid()
       {
           return id;
       }
       
       Item(string _name, int _id)
       {
            name = _name;
            id = _id;
            writename();
       }
};

void FindItem(int id)
{
     /* This takes the parameter and uses a loop to look through
     all of the Item class objects. But how...? */
}

int main()
{
    Item * rock = new Item("Rock", ITEM_ROCK);
    Item * stone = new Item("Stone", ITEM_STONE);
    int itemid = rock->getid();

    FindItem(itemid);
    
    system("PAUSE");
    return 0;
}


I want to, like the comment says, use an id as a parameter for a function that can look through all of the class's objects in search of the given id. I just don't know how that can be done.

P.S: I don't want to use an array of class objects. They suck.
Last edited on
You need an array or a container class that contains a bunch of these objects. Then you can iterate through the objects and find the one you are looking for.

1
2
3
4
5
6
7
8
9
10
11
Item* array[2];
array[0] = new Item("Rock", ITEM_ROCK);
array[1] = new Item("Stone", ITEM_STONE);

for (int i = 0; i < 2; i++)
{
    if (array[i]->getId == ITEM_ROCK)
    {
        array[i]->writename();
    }
}
Topic archived. No new replies allowed.