๐ 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 :