STL Algorithms in C++
STL algorithms work on iterator ranges, separating logic from container type. Combined with lambdas, they replace most hand-written loops.
sort and find
#include <algorithm>
#include <vector>
std::vector<int> v = {3, 1, 4, 1, 5};
std::sort(v.begin(), v.end());
auto it = std::find(v.begin(), v.end(), 4);
transform
std::vector<int> src = {1, 2, 3};
std::vector<int> dst(3);
std::transform(src.begin(), src.end(), dst.begin(),
[](int x) { return x * x; });
accumulate
#include <numeric>
int sum = std::accumulate(v.begin(), v.end(), 0);
double avg = sum / static_cast<double>(v.size());
Lambdas
auto is_even = [](int n) { return n % 2 == 0; };
auto count = std::count_if(v.begin(), v.end(), is_even);
// Capture: [=] by value, [&] by reference
int threshold = 10;
std::erase_if(v, [&](int x) { return x < threshold; });
Ranges (C++20)
#include <ranges>
auto evens = v | std::views::filter([](int x){ return x % 2 == 0; });
for (int x : evens) std::cout << x;
Common Pitfalls
- Ignoring compiler or linter warnings until they become production bugs.
- Skipping error handling on I/O, allocation, and network operations.
- Using outdated patterns when modern idioms exist in your language version.
- Testing only the happy path without edge cases and failure modes.
Best Practices
- Write tests alongside implementation, not after.
- Prefer explicit, readable code over clever one-liners.
- Use the standard library before reaching for third-party dependencies.
- Profile before optimizing; measure after.
- Document public APIs and non-obvious invariants.
Memory and Performance Notes
Algorithms don’t allocate. They operate in-place or write to output iterators.
Exercise
Use std::sort with custom comparator to sort strings by length, then alphabetically.
Hint: Pass [](const auto& a, const auto& b) comparators to sort.
Real-World Application
Production codebases combine these fundamentals with logging, metrics, and error recovery. Study mature open-source projects in this language for idiomatic patterns.
Summary
Master this topic through hands-on practice before advancing to the next section in the learning path.
Debugging Checklist
- Reproduce with minimal input.
- Read error messages completely.
- Binary-search the problem space by commenting out code.
- Compare against a known-good reference implementation.
- Write a regression test once fixed.
Quick Reference
Review the code examples on this page and type them manually — muscle memory accelerates learning.
Further Reading
C++ Core Guidelines, cppreference.com, and Effective Modern C++ by Scott Meyers.
Real-World Context
These patterns appear in Chromium, Unreal Engine, PostgreSQL, and countless production systems.
Additional Examples
Consider how this topic applies in a larger project:
// Break the problem into smaller functions
// Test each function independently
// Integrate incrementally
Working through variations of the examples above builds deeper understanding than reading alone.
Interview and Review Questions
- Explain the core concept of this topic in your own words.
- What happens when this code runs with edge-case input (empty, null, zero, max value)?
- How would you debug a bug related to this topic in production?
- What are the performance implications of the approach shown here?
- How does this feature compare to the equivalent in another language you know?
Related Topics in This Path
Review adjacent pages in the learning path before and after this one. Concepts build on each other — skipping ahead often leads to confusion when later pages assume mastery of earlier material.
Return to the section index if you need to fill gaps in prerequisite knowledge.
Tooling Tips
- Enable all compiler or analyzer warnings during development.
- Use version control with small, focused commits for each exercise.
- Pair reading with typing — reproduce every code example by hand.
- Run tests or compile after every change to catch errors early.
- Keep a personal notes file linking concepts to your own project experiences.