trouble with vectors

I'm having trouble with a vector which contains objects of class type Card (a class I needed to write myself). While troubleshooting I found that the vector has the right number of Cards created in it when I call push_back, namely 52, at the end of the contructor. However when I call separate functions, in particular the one I'm trying to troubleshoot is shuffle(), the vectors size is zero. The program compiles fine. I've included a copy of my function definitions as well as my main function below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
DeckOfCards::DeckOfCards() {
  srand( time(NULL) );
  vector<Card> deck;
  currentCard = 0;
  for ( int i = 0; i < 4; i++ ) {
    for ( int j = 0; j < 13; j++ )
      deck.push_back( Card( j, i ) );
  }
  cout << "Deck size at end of constructor: " << deck.size() << endl;
  cout << "Calling shuffle function in constructor.\n";
  shuffle();
}

void DeckOfCards::shuffle() {
  int randNum;
  Card temp;
  cout << "Deck size in shuffle function: " << deck.size() << endl;
  for ( int i = 0; i < deck.size(); i++ ) {
    randNum = rand() % deck.size();
    temp = deck[i];
    deck[i] = deck[randNum];
    deck[randNum] = temp;
  } 
}

Card DeckOfCards::dealCard() {
  Card retVal = deck.at(currentCard);
  currentCard++;
  return retVal;
}

bool DeckOfCards::moreCards() {
  return currentCard < deck.size();
}


1
2
3
4
5
6
7
8
9
int main() {
  DeckOfCards deck;
  deck.shuffle();

  while( deck.moreCards() )
    cout << deck.dealCard().toString() << endl;
  
  return 0;
}


When I run the program, the output looks like this:

Deck size at end of contructor: 52
Calling shuffle function in constructor
Deck size in shuffle function: 0
Deck size in shuffle function: 0

Any ideas as to my problem?
Last edited on
Try this:

1
2
3
4
5
6
7
8
9
10
11
12
DeckOfCards::DeckOfCards() {
  srand( time(NULL) );
  //vector<Card> deck; // <- comment this out
  currentCard = 0;
  for ( int i = 0; i < 4; i++ ) {
    for ( int j = 0; j < 13; j++ )
      deck.push_back( Card( j, i ) );
  }
  cout << "Deck size at end of constructor: " << deck.size() << endl;
  cout << "Calling shuffle function in constructor.\n";
  shuffle();
}

That worked perfectly. Thank you very much.
Topic archived. No new replies allowed.