IntermediateLesson 12 of 18
STL: Containers, Algorithms and Lambdas – C++
map, set, sort, find, transform and lambdas – the toolbox of the standard library.
The STL separates containers (data), iterators (position) and algorithms (operations). <algorithm> and <numeric> provide ready-made, well-tested functions – before you write a loop, it is worth having a look there.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> v{5, 3, 8, 1, 9, 2};
std::sort(v.begin(), v.end()); // 1 2 3 5 8 9
auto it = std::find(v.begin(), v.end(), 8);
if (it != v.end()) std::cout << "8 at index " << (it - v.begin()) << '\n'; // 4
int summe = std::accumulate(v.begin(), v.end(), 0);
std::cout << summe << ' ' << *std::max_element(v.begin(), v.end()) << '\n'; // 28 9
}Lambdas are anonymous functions. In [] you specify which variables are captured: [x] by copy, [&x] by reference, [=] everything copied, [&] everything by reference.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3, 4, 5, 6};
int faktor = 10;
auto mal = [faktor](int x) { return x * faktor; };
std::vector<int> ergebnis;
std::transform(v.begin(), v.end(), std::back_inserter(ergebnis), mal);
for (int x : ergebnis) std::cout << x << ' '; // 10 20 30 40 50 60
std::cout << '\n';
// Erase-remove idiom: delete even numbers
v.erase(std::remove_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }), v.end());
for (int x : v) std::cout << x << ' '; // 1 3 5
std::cout << '\n';
std::cout << std::count_if(v.begin(), v.end(), [](int x) { return x > 1; }) << '\n'; // 2
}std::map (sorted, tree) and std::unordered_map (hash table, usually faster) manage key-value pairs; std::set stores unique values. With structured bindings, you iterate elegantly:
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
std::vector<std::string> woerter{"b", "a", "b", "c", "b", "a"};
std::map<std::string, int> zaehler;
for (const auto& w : woerter) ++zaehler[w];
for (const auto& [wort, anzahl] : zaehler)
std::cout << wort << ": " << anzahl << '\n'; // a: 2, b: 3, c: 1
if (auto it = zaehler.find("z"); it == zaehler.end())
std::cout << "z missing\n";
}TipSince C++20, there is
std::erase_if(v, pred) as a shorthand for the erase-remove idiom and m.contains(key) for maps. Sort with a custom criterion via lambda: std::sort(v.begin(), v.end(), [](const auto& a, const auto& b){ return a.alter < b.alter; }).Warning
m[key] creates a new entry if the key is missing (even when just reading!). To look something up, use find, at or contains. A lambda that captures references ([&]) must not outlive the captured variables.