STL Algorithms
Master the power of <algorithm> in C++: learn to sort, find, and count with clean, expressive code that replaces hand-written loops.
What Are STL Algorithms?
The Standard Template Library (STL) provides a collection of pre-built functions in the <algorithm> header that operate on ranges of elements. Instead of writing loops by hand, you call a well-tested function.
Why Use STL Algorithms?
The Iterator Pattern
The Big Three: sort, find, count
std::sort: Syntax and Behavior
#include <vector>
std::vector<int> v = {5, 3, 8, 1, 9, 2};
// Sort ascending (default)
std::sort(v.begin(), v.end());
// v is now {1, 2, 3, 5, 8, 9}
// Sort descending with comparator
std::sort(v.begin(), v.end(), std::greater<int>());
// v is now {9, 8, 5, 3, 2, 1}
std::find: Searching for a Value
auto it = std::find(v.begin(), v.end(), 8);
if (it != v.end()) {
std::cout << "Found at index: "
<< (it - v.begin());
// Output: Found at index: 2
} else {
std::cout << "Not found";
}
std::count: Counting Occurrences
int n = std::count(v.begin(), v.end(), 3);
std::cout << n; // Output: 3
find vs count: When to Use Each
How to Apply STL Algorithms
Example 1: Sort Student Scores
#include <vector>
#include <iostream>
int main() {
std::vector<int> scores = {88, 72, 95, 64, 81};
std::sort(scores.begin(), scores.end());
for (int s : scores)
std::cout << s << " ";
// Output: 64 72 81 88 95
}
Example 2: Find a Target Value
auto it = std::find(names.begin(), names.end(), "Bob");
if (it != names.end()) {
std::cout << "Found " << *it
<< " at position "
<< (it - names.begin());
// Output: Found Bob at position 1
}
Example 3: Count and Sort Together
// Count how many 2s exist
int twos = std::count(data.begin(), data.end(), 2);
std::cout << "Twos: " << twos; // 3
// Sort then find the first 2
std::sort(data.begin(), data.end());
// data: {2, 2, 2, 4, 5, 7, 9}
auto it = std::find(data.begin(), data.end(), 2);
// it points to index 0
Visualizing std::sort
Common Mistakes
Summary Comparison Table
| Feature | std::sort | std::find | std::count |
|---|---|---|---|
| Purpose | Order elements | Locate a value | Tally a value |
| Arguments | begin, end [, comp] | begin, end, value | begin, end, value |
| Returns | void | iterator | integer |
| Complexity | \( O(n \log n) \) | \( O(n) \) | \( O(n) \) |
| Modifies data? | Yes | No | No |
| Can stop early? | N/A | Yes | No |
Question 1 of 5
What does std::sort(v.begin(), v.end()) return?
Question 2 of 5
Given std::vector<int> v = {4, 7, 2, 7, 3}, what does std::count(v.begin(), v.end(), 7) return?
Question 3 of 5
What happens if you dereference the iterator returned by std::find when the value is not found in the container?
Question 4 of 5
Which header must you include to use std::sort, std::find, and std::count?
Question 5 of 5
You want to check if a std::vector contains the value 42, but you do not need to know how many times it appears. Which approach is most efficient?