我正在开发一款游戏。我的玩家存储在 vector 中,在游戏结束时,当尝试将高分插入正确位置时游戏崩溃。
这是我的(请忽略葡萄牙语评论,代码非常简单:P):
//TOTAL_HIGHSCORES is the max. number of hiscores that i'm willing to store. This is set as 10.
bool Game::updateHiScores()
{
bool stopIterating;
bool scoresChanged = false;
//Se ainda nao existirem TOTAL_HISCORES melhores pontuacoes ou se a pontuacao for melhor que uma das existentes
for (size_t i = 0; i < players.size(); ++i)
{
if (hiScores.empty())
checkForValues = true;
else
checkForValues = (hiScores.size() < TOTAL_HISCORES || hiScores.back() < players[i].getScore());
if (players[i].getScoreValue() > 0 && checkForValues)
{
scoresChanged = true;
if(hiScores.empty() || hiScores.back() >= players[i].getScore())
hiScores.push_back(players[i].getScore());
else
{
//Ciclo que encontra e insere a pontuacao no lugar desejado
stopIterating = false;
for(vector<Score>::iterator it = hiScores.begin(); it < hiScores.end() && !(stopIterating); ++it)
{
if(*it <= players[i].getScore())
{
//E inserida na posicao 'it' o Score correspondente
hiScores.insert(it, players[i].getScore());
//Verifica se o comprimento do vector esta dentro do desejado, se nao estiver, este e rectificado
if (hiScores.size() > TOTAL_HISCORES)
hiScores.pop_back();
stopIterating = true;
}
}
}
}
}
if (scoresChanged)
sort(hiScores.begin(), hiScores.end(), higher);
return scoresChanged;
}
我在这里做错了什么?
谢谢你的时间,伙计们。
编辑:
我最终将我的代码简化为:
bool scoresChanged;
vector<Score> hiScoresCopy = hiScores;
for (size_t i = 0; i < TOTAL_PLAYERS; ++i)
hiScoresCopy.push_back(players[i].getScore());
sort(hiScoresCopy.begin(), hiScoresCopy.end(), higher);
scoresChanged = (hiScores != hiScoresCopy);
if (scoresChanged)
{
if (hiScoresCopy.size() > TOTAL_HISCORES)
hiScoresCopy.resize(TOTAL_HISCORES);
hiScores = hiScoresCopy;
}
return scoresChanged;
最佳答案
您没有确切说明代码崩溃的位置或崩溃的性质,所以我会猜测。
这个测试是错误的方法。
it < hiScores.end() && !(stopIterating)
在一种常见情况下,您的迭代器 it
将在您设置的同一子句中失效 stopIterating
为真。
您可以这样做(对于迭代器,!=
比 <
更符合惯用语,尽管两者都适用于 vector )。
!stopIterating && it != hiScores.end()
或者,在插入之后你可以只得到 break;
声明并取消 stopIterating
多变的。我认为这对于代码的大多数读者来说会更清楚。
关于C++ bughunt - vector 中的高分插入会使程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2888906/