Reversing: std::reverse
A high-score table starts with the best score, but std::sort puts the smallest value first. The algorithm std::reverse turns the order of a range around: the last element becomes the first, and the first one the last. Sort first, then reverse, and the largest value is at the front:
std::vector<int> scores = {640, 1250, 380, 980, 720};
std::sort(scores.begin(), scores.end());
std::reverse(scores.begin(), scores.end());
for (int i = 0; i < scores.size(); i++) {
std::cout << i + 1 << ". " << scores[i] << std::endl;
}This prints:
1. 1250
2. 980
3. 720
4. 640
5. 380The order of the two lines matters. std::reverse doesn't sort anything: it only turns around the order the elements are in. On its own, it would give you 720 980 380 1250 640, the unsorted scores back to front. And if you reversed first and sorted after that, the sort would undo the reversing.
A string is a sequence of characters, so it has begin() and end() too, and the algorithms work on it as on a vector of chars:
std::string word = "stressed";
std::reverse(word.begin(), word.end());
std::cout << word << std::endl;This prints desserts. In the Loops lesson, you printed this word backwards with a loop that counted down. std::reverse does it in one line, and it changes the string itself, so you can go on working with the reversed string. Only reverse strings without accents: a letter with an accent takes two chars, and reversing would swap them and break the letter.
In the next exercise, you will see how to sort from the largest value right away, without reversing.
Instructions
- 1
The high-score table should start with the best score. Below the line that sorts
scores, reverse the vector withstd::reverse. The table then starts with1. 1250and ends with5. 380. Keep the line with the scores as it is. - 2
The inscription on a door in the dungeon is written backwards. Before the line that prints it, reverse the string
inscriptionwithstd::reverse. The program printsThe door says: open sesame.