C++ Algorithm
⚙️ C++ Algorithms (STL)
The C++ Standard Template Library (STL) provides a powerful set of algorithms in the <algorithm> header.
These algorithms work on ranges of elements defined by iterators, not on containers directly.
1. Why Use STL Algorithms?
Ready-made, optimized solutions
Cleaner and shorter code
Work with all STL containers
Reduce bugs and improve performance
2. Include Header
3. Sorting Algorithms
sort() (Most Used)
Descending order:
stable_sort()
Preserves relative order of equal elements.
4. Searching Algorithms
find()
binary_search() (Sorted Required)
lower_bound() and upper_bound()
5. Counting Algorithms
Conditional count:
6. Min / Max Algorithms
7. Modify Sequence Algorithms
reverse()
replace()
remove() + erase() (Important!)
8. Accumulate & Numeric Algorithms
9. Partitioning Algorithms
10. Heap Algorithms
11. Set Algorithms (Sorted Required)
12. Algorithms with Lambdas
13. Common Algorithm Complexity
| Algorithm | Complexity |
|---|---|
| sort | O(n log n) |
| find | O(n) |
| binary_search | O(log n) |
| count | O(n) |
❌ Common Mistakes
✔ Use:
📌 Summary
STL algorithms operate on iterator ranges
Independent of container type
Highly optimized and reusable
Combine with lambdas for expressive code
Core skill for C++ interviews and projects
