Sorting: std::sort
A high-score table, monsters from the weakest to the strongest, items by price: games are full of lists in order. To make one, a program has to sort the values. You could write a loop for that, but it's much trickier than the sum or the largest value from the Loops lesson. Luckily, C++ has sorting ready-made, together with dozens of other algorithms. An algorithm is a recipe that solves a task step by step, and the library <algorithm> holds many of them, already written and tested. This lesson shows the ones you will need most often.
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> scores = {640, 1250, 380, 980, 720};
std::sort(scores.begin(), scores.end());
for (int score : scores) {
std::cout << score << " ";
}
std::cout << std::endl;
return 0;
}This prints:
380 640 720 980 1250 std::sort puts the elements in order, from the smallest to the largest. It changes the vector itself: after the call, scores[0] is 380, and the original order is gone.
Why scores.begin() and scores.end(), and not just scores? An algorithm doesn't get a whole vector, but a range: where to start and where to stop. scores.begin() is the position of the first element, and scores.end() is the position after the last one, where the vector ends. Such a position in a vector is called an iterator. Later in this lesson, you will work with iterators yourself. For now, scores.begin(), scores.end() simply means “the whole vector”. std::sort(scores) doesn't compile: the error no matching function for call to 'sort' comes with the note requires 2 arguments, but 1 was provided.
Strings can be sorted too. std::sort compares the elements with <, so strings end up in the order of their character codes, as in the lesson on strings: uppercase letters come before lowercase ones.
std::vector<std::string> names = {"Troll", "bat", "Goblin", "Orc"};
std::sort(names.begin(), names.end());After this, names holds Goblin, Orc, Troll and bat. Letters with accents and letters of other alphabets have larger codes than all of a–z, so they would end up after z.
And don't forget #include <algorithm>. Here, a program may compile even without it, because <iostream> happens to include it, but other compilers don't promise that.
Instructions
- 1
The vector
scoresholds the best scores of a game. Below#include <iostream>, add#include <algorithm>, and sortscoresbefore the loop that prints them. The program printsScores: 380 640 720 980 1250. Keep the line with the scores as it is: the exercise also runs your program with other scores. - 2
Below that, sort the vector
monstersand print it the same way, on one line after the textMonsters:. Keep the line with the monsters as it is too. The program printsMonsters: Bat Goblin Orc Slime Troll.