I have a problem with the std::sort-method. In the following code I'm using the std::sort-method to sort a vector of structs (= Highscore). However, when I run this line a "read access violation" exception is thrown in the xmemory-file.
Here are the details: Exception thrown: read access violation. _Pnext was 0x217AE3EE9D8. occurred
This is the method where the error occures.
void HighscoreManager::sortAndChangeRanks(bool deleteLast) {
std::sort(_highscores.begin(), _highscores.end());
if (deleteLast && _highscores.size() > MaxHighscores) {
_highscores.pop_back();
}
for (int i = 0; i < _highscores.size(); i++) {
_highscores.at(i).rank = i + 1;
}
}
_highscores is defined as std::vector<Highscore> _highscores;
and is filled with values from a file before the method call. This works just fine. When im debugging right before using the sort-Method, the vector is filled with the right values from the file.
This is the implementation of the Highscore-struct:
struct Highscore {
int rank;
std::string name;
int points;
Highscore() {}
Highscore(int r, std::string n, int p) : rank(r), name(std::move(n)), points(p) {}
bool operator<(const Highscore& h1) const {
return points < h1.points;
}
};
Please help me or point me to a direction where the error could lie, I'm out of ideas.
EDIT
Since it was asked in the comments where the vector is used before the call to std::sort, this is the method which is called from the object constructor and the only time the vector is used before the sorting. This way of reading (writing works similarly) from a binary file is based on this.
bool HighscoreManager::loadFromFile() {
std::ifstream in(FileName, std::ios::in | std::ios::binary);
if(!in) {
return false;
}
try {
std::vector<Highscore>::size_type size = 0;
in.read((char*)&size, sizeof(size));
_highscores.resize(size);
in.read((char*)&_highscores[0], _highscores.size() * sizeof(Highscore));
} catch(const std::exception& e) {
std::cout << e.what() << std::endl;
}
in.close();
sortAndChangeRanks(false);
return in.good();
}