I have a “raffle” C++ program that I use to “draw out of a hat”. I receive an EXC_BAD_ACCESS signal when I try to use it, though. Here is the function:
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;
}
This function 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.
The class Player contains an int speed. I call this function like this:
order=speedRaffle(players,pNum);
where players is vector and pNum is int. What am I doing wrong?
1. You are trying to access element at index
kin empty vectororderIt crashes because vector
orderis empty when you callorder[k] = *iter;, you should usepush_backfunction instead:order.push_back(*iter);.2. You use loop for “moving” iterator instead of simple
advancecalladvance(iter, randy - 1);has same effect as this loop:for(int i=0;i<randy;i++){ iter++; }.3. You call
powin 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
playersis 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 asconstwould 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
pNumargument if it’s equal toplayers.size().Hope this will help you.