STL Algorithms in C++: Searching, Sorting, Modifying, and Processing Data
What is STL Algorithms in C++: Searching, Sorting, Modifying, and Processing Data? STL algorithms in `` and `` are generic function templates that operate on sequences defined by iterator pairs `[first, last)`. They accept unary/binary callabl...
How do STL algorithms in `<algorithm>` work with lambdas and custom predicates to process container data?
Explanation & In-Depth Details
- Non-modifying: `std::find`, `std::count_if`, `std::all_of`, `std::any_of`
- Modifying: `std::transform`, `std::replace`, `std::copy_if`, `std::reverse`
- Sorting / Partitioning: `std::sort`, `std::stable_sort`, `std::partition`
- Numeric: `std::accumulate`, `std::inner_product`, `std::iota`
```text
ITERATOR RANGE PIPELINE:
[first] ──► element ──► Predicate / Transform ──► [last)
```
Code Example
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
int main() {
std::vector<int> scores = {85, 42, 95, 78, 60, 91, 53};
// 1. Counting with lambda predicate
int highScorers = std::count_if(scores.begin(), scores.end(), [](int s) {
return s >= 80;
});
std::cout << "Students with >= 80%: " << highScorers << "\n";
// 2. Transforming data in-place
std::transform(scores.begin(), scores.end(), scores.begin(), [](int s) {
return s + 5; // Add 5 curve bonus points
});
// 3. Sorting in descending order
std::sort(scores.begin(), scores.end(), std::greater<int>());
std::cout << "Curved & Sorted Scores: ";
for (int s : scores) std::cout << s << " ";
std::cout << "\n";
return 0;
}Interview Question & Tips
A: `std::sort` uses Introsort ($O(N \log N)$ average) but does not preserve the relative order of equivalent elements. `std::stable_sort` preserves equal elements order, using merge sort with $O(N \log N)$ time.
Q: Why are STL algorithms faster than passing function pointers in C?
A: In C++, template algorithms allow function objects and lambdas to be inlined directly at compile-time by the compiler, eliminating function call overhead.
Best Practices
• Avoid modifying containers (insert/erase) during an active algorithm traversal over that container.
• Use `std::binary_search` or `std::lower_bound` only on already sorted collections for $O(\log N)$ lookup.
This study reference for STL Algorithms in C++: Searching, Sorting, Modifying, and Processing Data is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: