This is the math:
Use vectors to implement a high score list for a video game. Make it so that scores are updated
automatically, and new scores are added into the right place in the list.
Problem is my program cann't add more than 5 elements to the list, and it's not in order as i expect. Blow up my mind and still got stuck. plz help.
Why do you use a separate addScore() function?
Simply add the score with push_back(), then sort the vector. For sorting it, use std::sort() from algorithm.
If a reallocation happens, all iterators, pointers and references related to the container are invalidated.
Otherwise, only those pointing to position and beyond are invalidated, with all iterators, pointers and references to elements before position guaranteed to keep referring to the same elements they were referring to before the call.
It is possible, in the code below, that insert() will invalidate the iterator itr.
General advice: do not insert new elements inside a for() loop where you iterate the original elements.
1 2 3 4 5 6 7
for (itr = (*listScore).begin(); itr != (*listScore).end(); itr++) //if input score is bigger than the current score,
{ //put the input in front of it
if (inputScore >= *itr)
{
(*listScore).insert(itr, inputScore);
}
}