[英]Shuffling function not working properly
I have created a shuffling program that uses a 5X5 array and a vector.我创建了一个使用 5X5 数组和向量的改组程序。 The vector should store the values 1 through 25 inclusive and the array should just have 0 for each element.
向量应该存储 1 到 25 的值,并且数组的每个元素应该只有 0。 Once the shuffle() function is passed it should randomly position the 1 through 25 values of the vector in the array.
一旦 shuffle() 函数被传递,它应该在数组中随机定位向量的 1 到 25 个值。
void Match::shuffle() {
std::vector<int> vec(25);
int randNum = rand() % (vec.size());
for (int i = 1; i < 26; i ++) {
vec.push_back(i);
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
backArr[i][j] = vec.at(randNum);
vec.erase(vec.begin() + randNum);
randNum = rand()%vec.size();
}
}
} }
In the last run (ie, after backArr[i][j]
has been set) you remove the last element from the vector and calculate randNum = rand()%vec.size();
在最后一次运行中(即,在设置
backArr[i][j]
之后)您从向量中删除最后一个元素并计算randNum = rand()%vec.size();
which calculates rand() % 0
which will fail.计算
rand() % 0
会失败。
Just calculate randNum
before backArr[i][j] = vec.at(randNum);
只需在
backArr[i][j] = vec.at(randNum);
之前计算randNum
backArr[i][j] = vec.at(randNum);
(also remove the randNum
in front of the loops). (也删除循环前面的
randNum
)。
Addendum: As pointed out by @infixed in the comments, you also create a vector of 25 (default-initialized) elements and afterwards push 25 additional elements (due to this, the first part of my answer is actually not true).附录:正如@infixed 在评论中指出的那样,您还创建了一个包含 25 个(默认初始化)元素的向量,然后再推送 25 个附加元素(因此,我的答案的第一部分实际上不正确)。 To solve that, you either need to remove the
(25)
when declaring vec
or replace the push_back
instructions by corresponding vector accesses (mind the off-by-1).要解决这个问题,您需要在声明
vec
时删除(25)
或用相应的向量访问替换push_back
指令(注意 off-by-1)。
为什么不使用 std::random_shuffle ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.