C++ Intermediate · Lesson 07 of 27
STL algorithms: sort, find and for_each
Expressing intent with <algorithm> instead of hand-written loops.
Estimated time · 45–75 min
Learning goals
What you will understand
- Explain stl algorithms: sort, find and for_each in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
The standard algorithms operate on iterator ranges [begin, end): the first position is included and the end position is one past the last element. sort orders a range, find_if locates the first match, for_each applies an action, and accumulate (in <numeric>) sums a range.
Algorithms take lambdas as the rule to apply. They are shorter, harder to get wrong than a raw index loop, and tell the reader what you mean. Sort a copy if the original order matters.
Guided lesson
Work through these steps
- 1.
Read the stl algorithms: sort, find and for_each example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
#include <algorithm>
// Header for sort, find_if, for_each and friends.
#include <numeric>
// Header for accumulate.
std::vector<double> temps{41.0, 85.5, 62.0, 90.1};
// Sample motor temperatures.
auto sorted = temps;
// Copy so the original order stays unchanged.
std::sort(sorted.begin(), sorted.end());
// Order the copy from smallest to largest.
auto hot = std::find_if(temps.begin(), temps.end(),
// Search for the first element matching the rule on the next line.
[](double t) { return t > 80.0; });
// The rule: temperature above 80. hot equals end() if nothing matches.
std::for_each(temps.begin(), temps.end(), [](double t) { std::cout << t << ' '; });
// Apply a printing lambda to every element.
double sum = std::accumulate(temps.begin(), temps.end(), 0.0);
// Add all values, starting from 0.0 (a double, so the sum is a double).What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Values in memory
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for STL algorithms: sort, find and for_each. Expected result: 41 85.5 69.65
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<double> temps{41.0, 85.5, 62.0, 90.1};
// TODO: sort a copy named sorted; find the first temperature above 80; compute the mean with accumulate
std::cout << sorted.front() << '\n' << *hot << '\n' << mean << '\n';
return 0;
}Expected output
41
85.5
69.65Stuck? Show the full solution (try it yourself first)
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<double> temps{41.0, 85.5, 62.0, 90.1};
auto sorted = temps;
std::sort(sorted.begin(), sorted.end());
auto hot = std::find_if(temps.begin(), temps.end(), [](double t) { return t > 80.0; });
double mean = std::accumulate(temps.begin(), temps.end(), 0.0) / temps.size();
std::cout << sorted.front() << '\n' << *hot << '\n' << mean << '\n';
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Given ten temperature samples, sort a copy, find the first value above 80 °C, count the values above 60 with std::count_if, and compute the mean with accumulate. Confirm that the original order is unchanged.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.