C++ Tutorial · Standard Library · Lesson 17 of 21
C++ Algorithms and Ranges
sort, find, accumulate, transform and C++20 ranges.
<algorithm> and <numeric>
The standard algorithms work on any container through iterators:
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> v{5, 2, 8, 1, 9, 4};
std::sort(v.begin(), v.end());
auto it = std::find(v.begin(), v.end(), 8);
std::cout << "found 8 at index " << (it - v.begin()) << '\n';
std::cout << std::accumulate(v.begin(), v.end(), 0) << '\n';
std::cout << *std::max_element(v.begin(), v.end()) << ' ' << std::count_if(v.begin(), v.end(), [](int n) { return n % 2 == 0; }) << '\n';
std::vector<int> doubled(v.size());
std::transform(v.begin(), v.end(), doubled.begin(), [](int n) { return n * 2; });
for (int n : doubled) std::cout << n << ' ';
std::cout << '\n';
}
Output
found 8 at index 4 29 9 3 2 4 8 10 16 18
Run this on your computer — see “Get Started” for setup.
Ranges (C++20)
std::ranges versions take the container directly, and views compose lazy pipelines with |:
#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<int> nums{5, 2, 8, 1, 9, 4};
std::ranges::sort(nums);
auto evensSquared = nums
| std::views::filter([](int n) { return n % 2 == 0; })
| std::views::transform([](int n) { return n * n; });
for (int n : evensSquared) std::cout << n << ' ';
std::cout << '\n';
for (int i : std::views::iota(1, 6) | std::views::reverse) std::cout << i << ' ';
std::cout << '\n';
}
Output
4 16 64 5 4 3 2 1
Run this on your computer — see “Get Started” for setup.
Test yourself
Which header provides std::accumulate?
<algorithm><numeric><math><functional>
Show answer
Answer: <numeric>