I'm struggling through a card program and want to pass my single card vector into my function so it can be used. Right now, I'd just like to test to see if it can print the cards from the deck, but passing it into a player hand is the ultimate goal. What's the best way to pass this vector for use in functions?
Thanks in advance!!
function to create deck:
void Deck::createDeck() {
deck.clear();
static const char suits[] = {'C','D','H','S'};
for (int suit=0; suit < 4; suit++)
for (int val=1; val <=13; val++)
deck.push_back(Card(val,suits[suit]));
}
function to pass the card to:
void Card::printCard(Card& drawnCard) const { //for debugging purposes
cout << value << " of " << suit << endl;
}
prototypes have been declared in header as follows:
class Card{
public:
int value;
char suit;
string drawnCard;
Card(int value, char suit) : value(value), suit(suit) {}
void printCard(Card& drawnCard) const;
};
class Deck {
public:
void createDeck();
void shuffleDeck(Card);
Card drawRandomCard();
Deck();
vector<Card> deck;
};
Thanks again!
There's a lot to critique here. You probably don't want to pass the list of cards directly, but probably want to pass the deck, instead, like:
void DoSomething(const Deck& deck) {
// ...
}
However, assuming you do pass the list, the way to pass it would be as a const reference:
void DoSomething(const std::vector<Card>& cards) {
// ...
}
There are many other areas, though, where your sample code could be improved. For example, the data fields of Card and Deck should probably be "private" and only accessed through accessor functions as appropriate. In addition printCard
does not need to take a Card as input, since it operates on this
(and, if it did take a parameter, a function that simply prints an object should take its parameter by a const, not a mutable reference).
See this gist for an example.