Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change an array with a function?

Tags:

c++

I'm quite new to C++ and I've ran across a problem.
I'm trying to write a game of Blackjack. I have an array of size 52 of type 'char' with the different cards and I want to shuffle it. I'm not sure how but that's not the problem. I made a function called 'ShuffleDeck' but it doesn't work, says it can't return an array. I can't reference the array either. How should I go about this? Here's the part of code I'm talking about.

void ShuffleDeck(bool &rgCards[]) {
    for (int i = 1; i < 52; ++i) {
        //something
    }
    return rgCards[];
}

All help appreciated.

like image 202
argoneus Avatar asked May 15 '26 00:05

argoneus


2 Answers

You use a std::vector and shuffle the values in it. Preferably, pass it by reference to the function and work on the original vector.

From your snippet, it's not entirely clear what you expect it to do - you pass an array of bool by reference but return it as an int with the syntax rgCards[] which makes absolutely no sense in that context.

EDIT: As per Fred's comment - you can use random_shuffle.

like image 185
Luchian Grigore Avatar answered May 17 '26 12:05

Luchian Grigore


From the code snippet you've provided it looks like you're trying to pass a reference to the array 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 make this a template function and have the compiler deduce the array length

template<size_t N>
void ShuffleDeck( char (&rgCards)[N] ) { ... }

Finally, since you're using C++ you should probably switch over to using a container class such as std::array or std::vector instead of a C-style array.

like image 42
Praetorian Avatar answered May 17 '26 13:05

Praetorian