<algorithm> and <numeric> provide tested, fast algorithms that work on containers:
std::sort(), std::reverse()
std::find(), std::count_if(), std::any_of()
std::accumulate(): sum or combine values
std::transform(): map values into another container
Pass lambdas to customise them.
💡 Key Takeaways: C++ STL Algorithms
Mastering C++ STL Algorithms helps you write clean and reliable C++ code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
C++ STL Algorithms Code Example
C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
int main() {
std::vector<int> v = {72, 95, 58, 88, 64};
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
int passed = std::count_if(v.begin(), v.end(), [](int m) { return m >= 60; });
int total = std::accumulate(v.begin(), v.end(), 0);
bool anyFail = std::any_of(v.begin(), v.end(), [](int m) { return m < 60; });
for (int m : v) std::cout << m << " ";
std::cout << "\nPassed: " << passed << ", total: " << total
<< ", any fail: " << std::boolalpha << anyFail << "\n";
return 0;
}