Finding a specific instance of a class

So I have a class that is like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class card
{

public:
    int id; 
    int val;

};

card card1; 
card1.id = 1;
card1.val = 2;

card card2;
card2.id = 2;
card2.val = 45; 

etc...

So my question is firstly, is there a better way to implement this? (a vector of classes or something maybe?) and how can I call up a specific instance of the class. For example, if I want the val of a specific instance of the class, how best can I do that?

Last edited on
vector, map, set, array .. pick your poison
Which is the best poison and could you possibly give a simple example (like mine above) of how to call up a specific instance of the class?
Your code fragment and question suggest you are a beginner? In that case, I would go for an array of objects.

(Remember to use code tags: the <> 'Format:' button to the right of this site's edit box will enter the required [code][/code] tags for you. Preferably, you'd go back and edit you original post to use tags?)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//snip

class card
{
public:
  int id;
  int val;
};

// snip

card cards[52]; // an array of 52 cards

card[0].id = 1; // first card is at index 0, as usual for C arrays
card[0].val = 2;

cards[1].id = 2;
cards[1].val = 45; 

// snip 


For information about vector, map, set, ... see:

Containers
http://www.cplusplus.com/reference/stl/

And
http://www.cplusplus.com/reference/vector/
http://www.cplusplus.com/reference/map/
http://www.cplusplus.com/reference/set/
etc...

Andy
Last edited on
Topic archived. No new replies allowed.