Lesson 19 of 19
STL Algorithms
STL Algorithms
The C++ Standard Library provides a rich set of algorithms in <algorithm> and <numeric> that operate on ranges (pairs of iterators). These algorithms replace hand-written loops with expressive, well-tested operations.
Sorting
std::sort sorts elements in ascending order by default:
#include <algorithm>
#include <vector>
vector<int> v = {5, 2, 8, 1, 9};
sort(v.begin(), v.end());
// v is now {1, 2, 5, 8, 9}
Searching
std::find returns an iterator to the first matching element:
auto it = find(v.begin(), v.end(), 8);
if (it != v.end()) {
cout << "Found: " << *it << endl;
}
Counting
std::count counts how many elements match a value:
vector<int> nums = {1, 2, 3, 2, 4, 2};
int twos = count(nums.begin(), nums.end(), 2);
// twos == 3
Accumulate (Sum / Fold)
std::accumulate (from <numeric>) computes a running total:
#include <numeric>
vector<int> v = {1, 2, 3, 4, 5};
int total = accumulate(v.begin(), v.end(), 0);
// total == 15
Transform
std::transform applies a function to each element and stores the result:
vector<int> src = {1, 2, 3};
vector<int> dst(3);
transform(src.begin(), src.end(), dst.begin(),
[](int x) { return x * x; });
// dst == {1, 4, 9}
Predicates: any_of / all_of
These test whether elements satisfy a condition:
vector<int> v = {2, 4, 6, 8};
bool allEven = all_of(v.begin(), v.end(),
[](int x) { return x % 2 == 0; });
// allEven == true
bool anyNeg = any_of(v.begin(), v.end(),
[](int x) { return x < 0; });
// anyNeg == false
Why Use STL Algorithms?
- Correctness — battle-tested implementations
- Readability —
sort(v.begin(), v.end())is clearer than a hand-rolled sort - Performance — optimized by compiler vendors
- Composability — algorithms chain together naturally
Your Task
Implement simplified versions of common STL algorithms as standalone functions:
bubbleSort— sort a vector of integers in ascending orderfindValue— return the index of a value (-1 if not found)countValue— count occurrences of a valueaccumulate— sum all elements starting from an initial value
Print the results as shown in the tests.
JSCPP loading...
Loading...
Click "Run" to execute your code.