finding the location of a vector after using rand(), srand()

hi there! i'm doing a card game and i'm unclear on how to retrieve the card by doing vectors. after i use use srand() in main and create a rand() in a function, how can i retrieve that random card 1-52?

so far i know that i have to find the length of the card. but i don't know why i have to save the location onto another variable and erase the card of the specified index before returning the card out the function. i'm very confused on this logic of vectors, if someone could speak in english what's exactly happening?

 
    int location = rand() % cards.size();   //i don't know why i need to do this and how do i reinitialize the variable cards into another variable? 
Not sure exactly what you are asking.

Perhaps you need to think in terms of a real physical pack of cards. You select one card at random from the deck, and pull it out. Now you have that card placed separately somewhere, and the deck itself has reduced in size as there is one card fewer.

When you emulate this in a program, it breaks down into a series of steps, which need to be done in a specific order.

so far i know that i have to find the length of the card.
that is, how many cards are in the deck. You need that in order to generate a random number within the correct range.
but i don't know why i have to save the location onto another variable
Well, having chosen a card by number, there are two actions required:
1. make a copy of the card which was stored in the vector
2. erase that element of the vector.
as a consequence of (2) the vector size will be reduced by one as well.

Either of these alone would not be sufficient. If you only erase it, then you no longer have access to that element so don't know what to return. Or if you only return that card but don't erase it, then later that same card may be chosen again, which doesn't correctly model the real world, where a card cannot be in two places at the same time.
You are calling function rand(). That in itself has nothing to do with vectors. See http://www.cplusplus.com/reference/cstdlib/rand/

Having read that, what you now can tell about the 'location' and its value?


Have you looked at the documentation of std::vector? http://www.cplusplus.com/reference/vector/vector/
It offers more than one way to access an element of the vector.
thanks Chervil that's exactly the answer to my question. i guess i didn't word it well enough for most ppl to understand but the problem with computer science for me is wording with real world examples to technical meanings of syntax. I need to learn how to somehow bridge the two better :P
Topic archived. No new replies allowed.