C++ Algorithms β Built-In Functions to Process STL Containers
Introduction β Why Use C++ STL Algorithms?
The STL (Standard Template Library) provides a powerful suite of generic algorithms to process containers using iterators. These algorithms save time, prevent errors, and improve performance by offering optimized implementations for tasks like sorting, searching, counting, and modifying elements.
In this guide, youβll learn:
- What STL algorithms are and how they work
- Categories: Non-modifying, Modifying, Sorting, Numeric, etc.
- How to apply algorithms using iterators
- Real-world examples and best practices
What Are C++ STL Algorithms?
C++ algorithms are defined in the <algorithm> and <numeric> headers and operate on ranges defined by begin and end iterators.
Include headers:
#include <algorithm>
#include <numeric>
Categories of STL Algorithms
| Category | Common Functions |
|---|---|
| Non-modifying | find(), count(), all_of(), any_of(), none_of() |
| Modifying | copy(), replace(), remove(), transform() |
| Sorting & Rearranging | sort(), reverse(), shuffle(), rotate() |
| Set Operations | set_union(), set_intersection() |
| Numeric | accumulate(), iota() |
Code Examples β With Output
Search with find()
#include <algorithm>
vector<int> v = {1, 2, 3, 4};
auto it = find(v.begin(), v.end(), 3);
if (it != v.end()) cout << "Found!";
Sort a Vector
sort(v.begin(), v.end()); // ascending
Count Occurrences
int n = count(v.begin(), v.end(), 2); // returns number of 2s
Sum Elements with accumulate()
#include <numeric>
int total = accumulate(v.begin(), v.end(), 0); // sum of all elements
Modify Elements with transform()
transform(v.begin(), v.end(), v.begin(), [](int x) { return x * 2; });
Most Commonly Used STL Algorithms
| Function | Description |
|---|---|
sort() | Sorts in ascending order |
find() | Finds first occurrence of value |
count() | Counts how many times a value appears |
reverse() | Reverses the container |
copy() | Copies elements from one range to another |
remove() | Removes value (requires erase() for actual removal) |
accumulate() | Sums a range of values |
Using Algorithms with Iterators
All STL algorithms work with:
- Containers that support iterators (
vector,list,set, etc.) - Iterators like
begin(),end(),rbegin(),const_iterator, etc.
Best Practices & Tips
Use range-based functions like for_each() with lambdas for clean syntax
STL algorithms are non-destructive by defaultβthey return copies unless told otherwise
Combine remove() with erase() to actually delete from containers (erase-remove idiom)
Prefer std::sort() over manual loops for efficiency and reliability
Use Cases for STL Algorithms
Sorting Data β Leaderboards, arrays, record sets
Searching β Locate items or duplicates
Aggregation β Calculate total, average, or summary
Game Logic β Detect win conditions, valid moves
Data Cleansing β Remove invalid or duplicate entries
Summary β Recap & Next Steps
Key Takeaways:
- STL algorithms offer reusable, efficient ways to manipulate containers
- Operate using iterators and require
<algorithm>or<numeric> - Improve performance, reduce boilerplate, and encourage generic programming
Real-World Relevance:
STL algorithms are widely used in systems programming, competitive coding, data science, finance, AI pipelines, and anywhere efficient collection manipulation is needed.
Next Steps:
Learn about C++ STL Containers & Adapters to understand how stack, queue, and priority_queue adapt sequence containers for specific behaviors.
FAQ β C++ Algorithms
Do STL algorithms modify the original container?
Some do (sort, reverse); others return results (remove, transform) that must be stored.
What if I want to remove elements?
Use the erase-remove idiom:
v.erase(remove(v.begin(), v.end(), value), v.end());
Can I use STL algorithms with sets and maps?
Yes, but you canβt modify the elements directly because they are immutable.
Do algorithms work with arrays?
Yes. Use raw pointers or begin(arr), end(arr) (C++11).
What is the difference between remove() and erase()?remove() moves the elements to be removed to the end. erase() physically deletes them.
Share Now :
