The STL and professional C++ · Lesson 18 of 21
Algorithms and lambdas
sort, find_if, count_if and accumulate, with one-line functions.
The <algorithm> header has dozens of ready-made functions that work on any container through iterators: begin() and end(). Instead of writing a loop each time, use them: quicker to write, well tested, and clearer to read.
A lambda is a small unnamed function written right where it's needed: [](int x) { return x > 50; }.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
struct Student {
std::string name;
int xp;
};
int main() {
std::vector<Student> s = {{"Laila", 320}, {"Karim", 150}, {"Omar", 90}, {"Nour", 410}};
std::sort(s.begin(), s.end(), [](const Student& a, const Student& b) { return a.xp > b.xp; });
for (const auto& st : s) std::cout << st.name << " ";
std::cout << "\n";
int threshold = 100;
auto above = std::count_if(s.begin(), s.end(), [threshold](const Student& st) { return st.xp > threshold; });
std::cout << above << " above " << threshold << "\n";
auto it = std::find_if(s.begin(), s.end(), [](const Student& st) { return st.name[0] == 'K'; });
if (it != s.end()) std::cout << "found " << it->name << "\n";
int total = std::accumulate(s.begin(), s.end(), 0, [](int sum, const Student& st) { return sum + st.xp; });
std::cout << "total " << total << "\n";
return 0;
}| Part | Meaning |
|---|---|
[] | captures nothing |
[threshold] | captures a copy of threshold |
[&total] | captures total by reference (can change it) |
[=] / [&] | everything it uses, by copy / by reference |
(int x) | parameters |
{ return … } | body |
What's the output?
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {5, 2, 8, 2, 9};
std::sort(v.begin(), v.end());
auto last = std::unique(v.begin(), v.end());
v.erase(last, v.end());
for (int x : v) std::cout << x;
std::cout << " " << v.size() << "\n";
}What will this code print?
Order the lines
Order the code that sorts names by length, shortest first.
- Click the lines in the right order
Exercise
From {7, 3, 10, 4, 15, 8}: sort the numbers in descending order and print them on one line, then the count of even numbers on a second line.
15 10 8 7 4 3 3
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {7, 3, 10, 4, 15, 8};
return 0;
}Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.