deaddeaddeads deaddeaddeads - 11 days ago 5
C++ Question

C++ Deal and Show a deck of cards with vector

I'm trying to deal 13 cards to 4 players with a vector array and then show the hands. But I am struggling to figure out how to deal the cards. I know I have to use pop and push in the deck to deal the cards, but I can't get anything to work. Any ideas would be helpful. I tried this so far,

void deal(vector<int> deck, int card[][cards], int players) {
for (int i = 0; i < players; i++) {
cout << "Player " << i + 1 << ": ";
for (int k = 0; k < cards; k++) {
deck.push_back(cards);
}
cout << endl;

}

}

Answer

while this seems to work

void deal(vector<int> deck, int card[][cards], int players) {

you're only updating a copy of your passed parameter. Once you exit of the function, your changes are lost for the caller.

I would suggest this: passing by reference:

void deal(vector<int> &deck, int card[][cards], int players) {

or even this:

vector<int> deal(int card[][cards], int players) {
   vector<int> deck;
   ...
   return deck;

which is more elegant (since your deck variable should be empty at start, so it's an out parameter, not an in/out paraemter) Nowadays compilers using return value optimization, it doesn't cost much than passing by reference. Let's not try to be smarter than the compiler.

Comments