C ++数组洗牌 [英] C++ Array Shuffle
问题描述
我是相当新的C ++和不明白的指针和引用函数参数。我有我想用费雪耶茨洗牌洗牌的数组。甲板被声明为
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.数组初始化。
那么我所说的随机播放功能:
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;
}
}
如果我尝试调用的随机播放功能,我收到了赛格故障后打印卡的价值。如何做到这一点的指针是否正确?
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?
推荐答案
看起来,你的问题并不来自于code发布,它看起来在乍看之下不错,但是从它周围的code
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 ++数组洗牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!