Algorithms
You could write your own loop to sort a vector or to find its largest value. In real C++ code, people rarely do. The <algorithm> header has ready-made functions for these common jobs. They are already tested, and they save you from writing the same loops again and again. You already used one of them, sort, in the Pairs lesson. Now you will see how it works.
sort
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> waits = {40, 10, 25, 10};
sort(waits.begin(), waits.end());
for (int w : waits) {
cout << w << " ";
}
cout << "\n";
return 0;
}
Output:
10 10 25 40
sort puts the values in order, smallest first. It changes the vector itself. It does not return a new vector.
Algorithms do not take the vector itself. They take a range: two iterators, where to start and where to stop. As you saw in the Iterators lesson, waits.begin() and waits.end() give you exactly that for the whole vector.
reverse and count
vector<int> waits = {10, 10, 25, 40};
reverse(waits.begin(), waits.end());
for (int w : waits) {
cout << w << " ";
}
cout << "\n";
cout << count(waits.begin(), waits.end(), 10)
<< "\n";
Output:
40 25 10 10
2
reverse flips the order of the values. count returns how many values are equal to its third argument. There are two 10s, so it returns 2.
min_element and max_element
cout << *min_element(waits.begin(), waits.end())
<< "\n";
cout << *max_element(waits.begin(), waits.end())
<< "\n";
Output:
10
40
These two do not return the value itself. They return an iterator to the smallest or largest value. To read the value, put a * in front, as you did with iterators.
Sorting from largest to smallest
sort can take a third argument that sets the order. greater<int>() means "larger values first":
vector<int> waits = {40, 10, 25, 10};
sort(waits.begin(), waits.end(), greater<int>());
for (int w : waits) {
cout << w << " ";
}
cout << "\n";
Output:
40 25 10 10
Be careful here. In the Priority Queues lesson, greater<int> put the smallest value on top. In sort, it puts the largest value first.
For any other order, such as sorting words by their length, you write your own rule. The next lesson, Lambdas, shows how.
In the exercise, read five scores into a vector, sort them, and print the sorted list with the lowest and highest score.