Help with a C++ Blackjack Project

Hello folks.

I'm currently taking a programming class, and I've got an assignment to write a basic Blackjack game in C++. I'm having some trouble writing the code I need to shuffle the deck before play can actually begin, and I was hoping someone would know how to help.

I'm starting by defining the deck as an array of strings, so I have:

string deck[52] = {"2","2"... etc. etc.}

In theory, I have the random_shuffle function called correctly, at least I think so:

1
2
srand(time(NULL)); 
random_shuffle(deck->begin(),deck->end()); 


After this, I just wanted to test to make sure the array was shuffled correctly, so I have:

1
2
3
4
5
for (int i=0; i<=51; i++)
{
cout << setw(4) << deck[i]; 
}
cout << endl;


When I run this in Visual Studio (by the way, pardon the "->" instead of a period, VS seems to like that better; the compiler didn't accept periods), it returns the array in the exact same order than I used to initially declare the deck.

Does anyone know what I'm missing?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>

int main()
{
	std::vector<std::string> cards = { "H2", "H3", "H4" , "H5", "H6" };

	std::cout << "before:";
	for (auto card : cards)
		std::cout << " " << card;
	std::cout << std::endl;

	std::random_shuffle(cards.begin(), cards.end());

	std::cout << "after:";
	for (auto card : cards)
		std::cout << " " << card;
	std::cout << std::endl;
}
So, would I want to use a vector instead of a regular array when using that shuffle function?
You should always prefer vector over array - arrays are a relic from C and pre C++98.
The use of vector instead of array has no bearing on whether shuffle works or not.

In general, vector is the default container to use if you're not sure what to use. It has some nice properties.

Arrays aren't really objects, they're sequences. And they're a little bit weird. For example, there's no way to pass them across functions, you end up passing a pointer, and so you loose the size. As you'll be doing object oriented programming, it's better to use an object container rather than an array.
Topic archived. No new replies allowed.