C++ Array Shuffle

后端 未结 10 1858
温柔的废话
温柔的废话 2021-01-07 14:06

I\'m fairly new to C++ and don\'t quite understand function parameters with pointers and references. I have an array of Cards that I want to shuffle using the Fisher-Yates

相关标签:
10条回答
  • 2021-01-07 14:38

    It looks that your problem does not come from the code posted, which looks fine at a first glance, but from the code around it.

    What about using a standard container of cards ? You must fill it, print it first to see if it's ok, shuffle, and then print it again.

    #include <vector>
    std::vector<Card> deck; // Empty for now. Must be filled with cards.
    
    
    void shuffle (std::vector<Card> & deck)
    {
        int deckSize = 24;
        while (deckSize > 1) 
        {
           long int k = lrand48();
           k = k %24;
           deckSize--;
           Card temp = deck[deckSize];
           deck[deckSize] = deck[k];
           deck[k] = temp;
        }
    }
    
    0 讨论(0)
  • 2021-01-07 14:40

    You declared deck as an array of pointers but you didn't allocate any space for it. If you de-reference it without allocating space you will get a seg-fault.

    0 讨论(0)
  • 2021-01-07 14:40

    Basic arrays can't be defined with variable passed as size, as mentioned above.

    And be careful there. Last element of

    typename array[SIZE];

    is array[SIZE-1], not array[SIZE]. It's probably where you getting a segfault.

    You really should at lest try to use STL containers. STL has shuffle algorithms too (:

    0 讨论(0)
  • 2021-01-07 14:42

    Just use std::random_shuffle found in <algorithm>, like this:

    std::random_shuffle(deck, deck + deckSize);
    

    and your deck with be shuffled.

    0 讨论(0)
  • 2021-01-07 14:46

    I think it might help to see the calling code.

    
    class Card{
    public:
        Card(int number):number_(number){}
        int getNumber(){return number_;}
     // ...
    private:
        int number_;
    };
    
    void shuffle (Card * deck[]) {
        int deckSize = 24;
        while (deckSize > 1) {
           long int k = lrand48();
           k = k %24;
           deckSize--;
           Card * temp = deck[deckSize];
           deck[deckSize] = deck[k];
           deck[k] = temp;
        }
    }
    
    int main(int argc, char* argv[]){
    {
    
      const int deckSize=24;
      Card* deck[deckSize];
      for(int i = 0 ; i getNumber()

    That should work just fine.

    0 讨论(0)
  • 2021-01-07 14:49

    You could also use

    std::random_shuffle(deck, deck + deckSize)

    which does Fisher-Yates for you.

    However, there probably aren't enough bits in the standard random libraries to genuinely choose from all possible random permutations of cards.

    0 讨论(0)
提交回复
热议问题