I'm trying to make a deck of cards; I want it to keep track of the cards that have been drawn. Will this code delete the card that is displayed?

void Deck::draw_card()
{         
     int random_card = (rand() % cards.size()) - 1;      
     
     cout << "\n" << cards[random_card].name << "\n";
     
     cards.erase(cards.begin() + random_card);
}

Recommended Answers

All 2 Replies

Well, you can easily find that out for yourself. Just create an iterator and run through the vector to see if it was erased or not.

vector<card>::iterator it = cards.begin();
for(; it != cards.end(); it++)
{
   cout it->name << '\n';
}

Can I just add, the code the OP has given will go horribly wrong at some point,
since int random_card = (rand() % cards.size()) - 1; can result in -1.

That will be a very strange output, and some memory violation later, most likely resulting in a core dump.

The -1 is not necessary.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.