# Adding cards to a vector for computer card game

I am writing a Card game that has a deck size of 30 cards, where each card has to be a unique object, stored in a vector.

Right now, my plan is to add them to a vector one at a time, with four separate (depending on what deck type you choose) sets of thirty .push_back functions. (ie. 120 push_back calls, divided into 4 blocks, one for each collection.)

Assuming the collections of cards are not up for customization, is there a quicker or simpler way of doing this, that doesn't involve typing out 120 separate push_back calls?

-
Excuse me, but...what? I lost you after the first comma. – Hackworth Apr 16 '12 at 3:23
I didn't think it was that bad, so I edited it to say what I think he meant. – Kylotan Apr 16 '12 at 9:52
@Kylotan Thankyou. :) – doppelgreener Apr 16 '12 at 10:08

Without knowing more about your specific sets of cards, my only suggestion would be to write some loops for the specific types of cards.

For example, with a standard 52 card deck, you have 14 faces and 4 suites. If you represent your suites as a simple enum and faces as another enum, with the card objects saved in the vector as a simple struct combining the two, you can have something short and sweet. Given the following explanatory definitions:

``````// definitions for our code
enum Face { ACE, TWO, THREE, /* etc */, FACE_COUNT };
enum Suite { DIAMOND, HEART, CLUB, SPADE, SUITE_COUNT };

struct Card {
Card(Face face, Suite suite) : face(face), suite(suite) {}

Face face;
Suite suite;
};
``````

You can use the following simple function to build the deck:

``````// code to build a deck
void build_deck(std::vector<Card>& cards)
{
for (int face = 0; face != FACE_COUNT; ++face)
for (int suite = 0; suite != SUITE_COUNT; ++suite)
cards.push_back(Card(Face(face), Suite(suite)));
}
``````

You said you have a 30 card deck, but didn't specify any other details. If there's some kind of way to break down the cards into sets of distinct attributes, however, you should be able to put together some kind of similar loops.

I might also suggest going for a data-driven approach if the cards aren't easily generated automatically. It at least would make it easy to update or change the lists without needing to edit a bunch of redundant code and recompile. Just generate a list for the card names, write one function that can take a name and push back the appropriate object into the vector, and then each arrangement of deck can just read from a different file.

-
+1 Thankyou for introducing a new programmer to a wonderful way to do things (writing out 120 push_back statements... augh) – doppelgreener Apr 16 '12 at 10:09