How can I change an array using a function?
I am new to C ++ and I am facing a problem.
I am trying to write a blackjack game. I have a 52 array of "char" type with different cards and I want to shuffle it. I'm not sure how this is not a problem. I made a function called "ShuffleDeck" but it doesn't work, says it can't return an array. I also cannot reference the array. How should I do it? Here is the piece of code I'm talking about.
void ShuffleDeck(bool &rgCards[]) {
for (int i = 1; i < 52; ++i) {
//something
}
return rgCards[];
}
All help was appreciated.
source to share
You use std::vector
and shuffle the values in it. It is preferable to pass it by reference to a function and work with the original vector.
It is not entirely clear from your snippet what you expect from it - you are passing the array bool
by reference, but returning it as int
with syntax rgCards[]
, which makes absolutely no sense in this context.
EDIT: as per Fred's comment - you can use random_shuffle
.
source to share
From the code snippet you provided, it looks like you are trying to pass an array reference to ShuffleDeck()
. The C ++ syntax for an array reference is data-type (&)[N]
, where N
is the number of elements in the array. Change your function to
void ShuffleDeck( char (&rgCards)[52] ) { ... }
You can do it as a template function and calculate the length of the array
template<size_t N>
void ShuffleDeck( char (&rgCards)[N] ) { ... }
Finally, since you are using C ++, you should probably switch to using a container class such as std::array
or std::vector
rather than a C type array.
source to share
To keep the code most similar to what you are writing, I'll just make minimal fixes: note that &
it is not required and the index must start at 0.
void ShuffleDeck(bool rgCards[]) {
for (int i = 0; i < 52; ++i) {
//something
}
}
any change you make to rgCards [i] will be available after calling ShuffleDeck
source to share