← C++ from Scratch
Lesson 61 of 62 · 10 XP
STL algorithms
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
<algorithm> and <numeric> hold dozens of ready-made algorithms that work through iterators with any container:
std::sort(v.begin(), v.end()); // sorting
std::sort(v.begin(), v.end(), std::greater<int>()); // in descending order
std::reverse(v.begin(), v.end());
auto it = std::max_element(v.begin(), v.end()); // an iterator to the maximum
std::count(v.begin(), v.end(), 0); // how many zeros
std::binary_search(v.begin(), v.end(), 7); // whether there's a 7 (v must be sorted)
v.erase(std::unique(v.begin(), v.end()), v.end()); // remove neighbouring repeats
std::accumulate(v.begin(), v.end(), 0); // the sum (<numeric>)
std::transform(v.begin(), v.end(), v.begin(), [](int x) { return x * 2; });
Writing your own sort is needed for understanding (as in the C course), but at work you use std::sort: it's fast
(introsort, O(n log n)) and bug-free.
Task. A high-score table. Read n lines of name score. Print the players by descending score, and on a tie —
by name; the format is place. name score. Then print the median score (for an even n — the average of the two middle ones, one decimal place).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.