C++
Summary - STL algorithms
Combine sort, find and accumulate to write a sales report.
Summary - STL algorithms
In this group you learned std::sort, std::find, std::count, std::transform and std::accumulate. Now we combine them in a sales report.
On a sales vector we will first sort with std::sort, then search for a specific sale with std::find. In the second step we compute the total sales with std::accumulate. This shows how STL algorithms work together in a real scenario.
Exercise Sort sales and search
Sort sales = {150, 80, 200, 90} in ascending order with std::sort. Then search for 150 with std::find and print "found" if present. Do not print the sorted list; print only the search result.
Show example solution
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> sales = {150, 80, 200, 90};
std::sort(sales.begin(), sales.end());
auto it = std::find(sales.begin(), sales.end(), 150);
if (it != sales.end()) {
std::cout << "found";
}
return 0;
}
Exercise Compute the total sales
Take the previous step's std::sort and std::find calls. Add #include <numeric> and compute the total of the sales vector with std::accumulate, then print it. Print the total on a new line after the "found" message.
Show example solution
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
int main() {
std::vector<int> sales = {150, 80, 200, 90};
std::sort(sales.begin(), sales.end());
auto it = std::find(sales.begin(), sales.end(), 150);
if (it != sales.end()) {
std::cout << "found";
}
int total = std::accumulate(sales.begin(), sales.end(), 0);
std::cout << total;
return 0;
}
STL algorithms recap
STL algorithms are generic functions that work on containers. std::sort sorts, std::find searches, std::count counts, std::transform maps, std::accumulate sums. All work with iterator ranges.
Their power is that they are independent of the container type. The same std::sort works on both std::vector and std::array. In the next group you will learn lambda expressions, which make passing conditions and operations to STL algorithms much more powerful.
Test yourself
-
Which algorithm finds the total of a vector?
std::vector<int> sales = {150, 80, 200};
- std::accumulate
- std::sort
- std::find
- std::count
Show answer
std::accumulate — std::accumulate sums the elements.
-
Complete the sort call
std::____(sales.begin(), sales.end());
Show answer
std::sort(sales.begin(), sales.end());
Next lesson: What are lambdas?