seedin a vector with 52 unique values

I am trying to seed a vector with 52 values ranging from 1 to 52. I already have the code written to seed the vector but I cant figure out how to keep from repeating the same values from being seeded. This is for a five card stud game.


#include<iostream>
#include<cmath>
#include<cstdlib>
#include<string>
#include<vector>
#include<ctime>
using namespace std;

int main()
{
int cardNum = time(0);
srand(cardNum);
vector<int> cardDeck(52);

for(int i = 0; i < 52; i++)
cardDeck[i] = rand() % 52 + 1;

for(int i = 0; i < 52; i++)
cout << cardDeck[i] << endl;



system ("PAUSE");
return 0;
}
The C++ function you're looking for is called random_shuffle() (or shuffle() if you want to use the C++ random number generators)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
#include <ctime>
#include <algorithm>

int main()
{
    int cardNum = std::time(0);
    std::srand(cardNum);

    std::vector<int> cardDeck(52);

    for(int i = 0; i < 52; i++)
        cardDeck[i] = i+1; // or just call std::iota

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

    for(int i = 0; i < 52; i++)
        std::cout << cardDeck[i] << '\n';
}
Hello, there are quite a few ways to accomplish this. Here is a 'modern' approach using standard constructs found in the <algorithm> header. Alternatively, you will have to explicitly check for duplicates each time you try to insert a new value (which might involve a nested for-loop).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
    std::vector<uint32_t> deck(52);
    uint32_t counter = 0;
    
    // Fill vector with values '1' to '52'
    std::generate(deck.begin(), deck.end(), [&](void)->uint32_t{return ++counter;});
    
    // Randomly shuffle the vector
    std::random_shuffle(deck.begin(), deck.end());
    
    // Print out what we've done
    for(int i = 0; i < 52; ++i)
    {
        std::cout << deck[i] << std::endl;
    }
}


* ninja'd on my first post back here on cplusplus. This can't be a good omen. :)
Last edited on
Thank you Luke and Cubbi. I have only taken C++ 1 in school and am taking C++ 2 next semester. I am using my holiday break to further my understanding of C++ language by creating card games. Both of your algorithms are great pieces for me to explore .
Topic archived. No new replies allowed.