Reputation: 649
I'm creating a simple program that can deal with playing cards. I've gotten to creating a hand, but I ran into a problem: when the hand is dealt, the cards are not removed from the deck. The deck is a vector of Card objects which contain suit, value and color.
This is just the short testing program I wrote for it:
Deck testDeck; //default deck is in order
cout << testDeck << endl; //print the deck out
Hand testHand(5, testDeck); //generate a hand of 5 cards from testDeck
cout << testHand << endl; //print the hand
cout << testDeck << endl; //print the deck
The initialized deck
2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH AH 2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD AD
2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC AC 2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS AS
Getting a sample hand of 5 cards from the deck
2H 3H 4H 5H 6H
The deck should be missing the 5 cards, but it just gives back the initial deck as if nothing happened.
2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH AH 2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD AD
2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC AC 2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS AS
This is my constructor for a hand:
Hand::Hand(int numCards, Deck myDeck)
{
myHand = myDeck.takeTopXCards(numCards);
}
Here's the takeTopXCards function:
vector<Card> Deck::takeTopXCards(int numCards)
{
vector<Card> retCards;
for(int i = 0; i < numCards; i++)
retCards.push_back(takeTopCard());
return retCards;
}
And of course, the TakeTopCard function:
Card Deck::takeTopCard()
{
Card ret = myDeck[0];
myDeck.erase(myDeck.begin());
return ret;
}
I've checked the takeTopCard function by printing myDeck[0] (myDeck being a private data member of the Deck class) before and after using erase and it works fine. For some reason, once takeTopXCards returns, the Deck object (testDeck in the testing program) passed to it doesn't change.
If you want to see anything else, just ask and I'll add it to the end here. Thanks.
Upvotes: 2
Views: 133
Reputation: 66194
Change this:
Hand::Hand(int numCards, Deck myDeck)
To this:
Hand::Hand(int numCards, Deck& myDeck)
Why:
You're passing the deck by-value, which is making a copy of it when dealing the hand. the copy is what is reduced. the original deck is not. Pass it by reference and the original deck will be modified.
Upvotes: 2