STL algorithms in C++
sort, find, count_if, accumulate, transform and friends, and why algorithms beat hand-written loops.
<algorithm> and <numeric> hold dozens of tested building blocks that work on any range:
std::sort,std::stable_sortstd::find,std::find_if,std::count_if,std::any_ofstd::accumulate(sum or fold),std::transform(map)std::lower_bound(binary search on sorted data)std::erase_if(C++20) to remove matching elements
Using a named algorithm says what the code does, and avoids off-by-one mistakes. C++20 ranges let you pass the container directly: std::ranges::sort(v).
Example
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> v{4, 8, 15, 16, 23, 42};
int total = std::accumulate(v.begin(), v.end(), 0);
bool has_odd = std::any_of(v.begin(), v.end(), [](int x) { return x % 2 != 0; });
std::erase_if(v, [](int x) { return x > 20; });
std::cout << total << " " << has_odd << " " << v.size() << "\n";
return 0;
}
Output:
108 1 4