抽奖排序程序上的 EXC_BAD_ACCESS
我有一个“抽奖”C++ 程序,我用它来“凭空抽奖”。不过,当我尝试使用它时,我收到了 EXC_BAD_ACCESS 信号。这是函数:
vector<int> speedRaffle(vector<Player>players,int pNum){
vector<int> spdtics,order;
int ticnum,randy;
vector<int>::iterator iter = spdtics.begin();
for (int k=0;k<pNum;k++){
for (int i=0; i<pNum; i++) {
for (int j=0; j<pow(players[i].speed,2); j++){
for (int io=0; io<order.size(); io++) {
if(order[io]!=i){
spdtics.push_back(i);
ticnum++;
}
}
}
}
randy=random() % ticnum;
for(int i=0;i<randy;i++){
iter++;
}
order[k]=*iter; //Thread 1: Program received signal: "EXC_BAD_ACCESS".
iter=spdtics.begin();
}
return order;
}
该函数应该获取所有玩家的速度并对它们进行平方。然后,它将那么多(速度的平方)“抽奖券”放入 spdtics 中。然后,它从 spdtics 中随机抽取一张“票”,并将拥有该票的玩家的号码排序。然后,再次重复,直到所有玩家都被抽中,而不是抽到同一个玩家两次。它返回玩家获胜的顺序。
Player 类包含一个 int speed。我这样称呼这个函数:
order=speedRaffle(players,pNum);
其中players是向量,pNum是int。我做错了什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1.您正在尝试访问空向量
order
中索引k
处的元素,它会崩溃,因为当您调用
时向量
,您应该使用order
为空>order[k] = *iter;push_back
函数:order.push_back(*iter);
。2.您使用循环来“移动”迭代器,而不是简单的
advance
调用advance(iter, randy - 1);
与此循环具有相同的效果:for(int i=0;i。
3.您在每次迭代中调用
pow
请注意,这会快得多:
4。使用索引可以直接访问向量中的元素
在这种情况下,您根本不需要任何迭代器。
5.按值传递向量而不是按引用传递
请注意,每次调用此函数时都会创建向量
players
的副本。你不想那样做。您也不想在函数内部更改此向量,因此将此参数声明为 const 会更好:6。您的代码没有执行您需要执行的操作
“它应该获取所有玩家的速度并对它们进行平方。然后,它将那么多(速度的平方)“抽奖券”放入 spdtics然后,它从 spdtics 中随机抽取一张“票”,并将拥有该票的玩家的编号排列起来,然后再次重复,直到抽出所有玩家,而不是重复抽出同一玩家。玩家获胜。”
据此,您的函数应如下所示:
另请注意,如果
pNum
参数等于players.size()
,则不需要它。希望这会对您有所帮助。
1. You are trying to access element at index
k
in empty vectororder
It crashes because vector
order
is empty when you callorder[k] = *iter;
, you should usepush_back
function instead:order.push_back(*iter);
.2. You use loop for "moving" iterator instead of simple
advance
calladvance(iter, randy - 1);
has same effect as this loop:for(int i=0;i<randy;i++){ iter++; }
.3. You call
pow
in every single iterationNote, that this would be much faster:
4. Elements in vector can be accessed directly by using index
You don't need any iterator at all in this case.
5. Passing vector by value instead of passing it by reference
Note, that copy of vector
players
is created every time you call this function. You don't want to do that. You also don't want to change this vector inside of function, so declaring this argument asconst
would be much better:6. Your code does not do what you need it to do
"It should take all of the players' speeds and square them. Then, it puts that many (the squares of speeds) "raffle tickets" into spdtics. It then randomly draws one "ticket" from spdtics, and puts the number of the player who owned the ticket into order. Then, it repeats again until all players have been drawn, not drawing the same player twice. It returns the order in which the players won."
According to this, your function should look like this:
Also note that you don't need
pNum
argument if it's equal toplayers.size()
.Hope this will help you.