Line 14: you are declaring the size of your vector, no need to
push_back values when assigning values to the elements. That extends the size of an already sized vector.
A vector keeps track of its size, why not use that?
1 2 3 4 5 6 7 8
|
void unwrap(std::vector<int> &deck)
{
//Load vector with ints from 0 to 51
for (int i = 0; i < deck.size(); i++)
{
deck[i] = i;
}
}
|
You are not displaying the deck, either before or after being shuffled. Add a display function:
1 2 3 4 5 6 7 8 9 10 11 12
|
void display(const std::vector<int>&);
.
.
.
void display(const std::vector<int>& deck)
{
for (auto loop = deck.cbegin(); loop != deck.cend(); loop++)
{
std::cout << *loop << ' ';
}
std::cout << '\n';
}
|
You want the vector's reference to be
const, it should not be allowed to be changed.
The
cbegin (constant begin) and
cend (constant end) iterators require C++11, hopefully your compiler supports it.
Your main could look like this now:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
int main()
{
//Declare vector for the number of cards
std::vector<int> deck(52);
// unwrap the deck (fill it with values
unwrap(deck);
// display the original, unsorted order
std::cout << "The deck before shuffling:\n";
display(deck);
// randomly shuffle the deck
shuffle(deck);
// display the shuffled deck
std::cout << "\nThe deck after being shuffled:\n";
display(deck);
}
|
The deck before shuffling:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
The deck after being shuffled:
41 6 18 44 26 0 7 32 37 48 2 20 24 39 47 19 25 33 22 38 4 1 31 10 45 30 40 49 28 29 34 35 50 46 12 17 14 11 15 36 43 23 13 9 42 27 16 3 8 51 5 21 |
Two things to note, for the future:
1.
std::random_shuffle uses the C-library
rand function for sorting the container. You forgot to seed
rand by using
srand. Not seeding will give you the exact same "random" numbers every time your program runs, giving your shuffled deck of cards the exact same order.
Not a good shuffle IMO.
2.
std::random_shuffle was deprecated in C++14 and removed from C++17. C++11 introduced
std::shuffle. It uses a C++ random engine, so you have to create and randomize one.
Modifying your code to use std::shuffle. Add a couple of
1 2
|
#include <random> // for default_random_engine
#include <chrono> // for system_clock
|
Change your shuffle function:
1 2 3 4 5 6 7 8
|
void shuffle(std::vector<int> &deck)
{
// create a C++ random engine, seeded with the system clock
std::default_random_engine rng(static_cast<unsigned> (std::chrono::system_clock::now().time_since_epoch().count()));
// shuffle the deck
std::shuffle(deck.begin(), deck.end(), rng);
}
|
I know that looks very scary and intimidating. First time seeing some new way to do C++ code can be. :)
You wrote some solid C++ code. With a few simple, easily correctable mistakes.