C ++ Array Shuffle [英] C++ Array Shuffle
问题描述
我对C ++相当新,不太了解函数参数和指针和引用。我有一个卡阵列,我想使用Fisher-Yates shuffle洗牌。甲板被宣布为
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 shuffle. The deck is declared as
Card *deck[deckSize];
其中deckSize已声明为24.然后初始化数组。
然后我调用shuffle函数:
where deckSize has been declared as 24. The array is then initialized. I then call the shuffle function:
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;
}
}
如果我尝试打印卡的值调用shuffle函数我得到seg故障。任何指示如何正确地这样做?
If I try to print the value of a card after calling the shuffle function I get a seg fault. Any pointers on how to do this properly?
推荐答案
看起来你的问题不是来自代码发布,乍一看,但从它周围的代码。
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;
}
}
这篇关于C ++ Array Shuffle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!