Modern C++ • C++20 baseline
Iterators and Standard Algorithms
Express common transformations with algorithms instead of duplicating loop logic.
Iterators connect containers to algorithms without requiring one container type. Algorithms such as std::find_if and std::count_if centralize common traversal patterns. Use named predicates or lambdas to make the condition visible, and remember that iterator invalidation is determined by the container.
Key points
- Algorithms operate on iterator ranges, conventionally [first, last).
- Use algorithms that communicate intent; a loop remains appropriate for complex stateful logic.
Example
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
const std::vector<int> values{3, 10, 7, 12};
const auto count = std::count_if(values.begin(), values.end(),
[](int value) { return value >= 10; });
std::cout << count << '\n';
}
What to expect
2
Practice exercise
Use std::remove_if followed by erase to remove values below a threshold. Explain why remove_if alone does not shrink the vector.
Key idea: Use the standard algorithms to make intent reusable and range boundaries explicit.