Hello, everyone!
I have a game I'm working on. My players are stored in a vector, and, at the end of the game, the game crashes when trying to insert the high-scores in the correct positions.
Here's what I have (please ignore the portuguese comments, the code is pretty straightforward :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;
}
What am I doing wrong here?
Thanks for your time, fellas.
EDIT:
I ended up simplifying my code to this:
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;