c++ - Vector losing data after coming out of function that writes to it -
i'm getting c++ after 10 year absence , decided try , program ascii blackjack game. decided use vector hold both deck , players hand finding when call initial deal function should assign 2 cards both dealer vector hand , player vector hand, writes cards fine when comes out , later on want print hand, out of bounds exception.
code snippets below!
void deck::initialdeal(player dealer, player player1) { for(int = 0; < 2 ; i++) { dealer.addhand(mydeck[i]); mydeck.erase(mydeck.begin()); player1.addhand(mydeck[i]); mydeck.erase(mydeck.begin()); } }
the above takes couple of cards main deck , calls addhand routine add card players vector hand:
void player::addhand(card dealtcard) { hand.push_back(dealtcard); }
if put in routine output hand vector inside addhand function, works fine , shows data put in.
however, later on want print hand screen , have function called printhand()
void player::printhand() { if (dealer == true) { cout << hand[0].getnumber() << hand[0].getsuit() << " "; cout << hand.size() << endl; } else { for(std::vector<card>::size_type x = 0 ; x != hand.size() ; x++) { cout << hand[x].getnumber() << hand[x].getsuit() << " "; } } }
at moment dealing dealer side, goes dealer branch of function , thats when error.
i have feeling should maybe have used pointers here because data created in addhand() function gets deleted once done?
you seem pass arguments by copy, , not reference (and reference not mean pointers). means modifying copies , not originals.
if modify function prototype this:
void initialdeal(player& dealer, player& player1)
the arguments passed reference instead, , allows modify original objects being passed arguments.
Comments
Post a Comment