Module 7 · Lambdas and algorithms
7.2Iterators and algorithms
Find, count, sort, add up and transform data with the standard algorithms instead of hand-written loops. Learn iterators and half-open ranges, the std::ranges versions with projections, and what breaks when a container changes while you loop over it.
On this page
- Key terms
- In 30 seconds
- Iterators: positions in a container
- Half-open ranges
- Finding and counting
- Sorting
- Smallest and largest
- Transforming every element
- Adding up: std::accumulate and std::reduce
- The std::ranges:: versions and projections
- Which one should I use?
- Under the hood
- Common pitfalls
- 0 instead of 0.0 in std::accumulate
- Changing a vector while looping over it
- Sorting a container without random-access iterators
- Try it yourself
Key terms
- iterator
- An object that marks a position in a container.
*itgives the element there and++itmoves to the next one.begin()returns the first position. - past-the-end iterator
- The iterator
end()returns: one past the last element. It has no element of its own, so you must not use*on it. - half-open range
- A pair of iterators
[first, last): it includes the element atfirstand stops just beforelast. Whenfirst == last, the range is empty. - comparator
- A function that takes two elements and returns
trueif the first should come before the second.std::sortuses one to decide the order. std::ranges::algorithms- Versions of the algorithms that take a whole container instead of two iterators, and accept a projection.
- projection
- A function a
std::ranges::algorithm applies to each element before comparing or testing it, such as&Read::qualityto sort reads by their quality. - pointer to member (
&Read::quality) - A way to name one member of a struct without naming an object. As a projection, it means use this member of each element.
- random-access iterator
- An iterator that can jump any distance in one step, like
it + 5. Iterators ofstd::vector,std::arrayandstd::stringare random-access;std::sortneeds them. - iterator invalidation
- When a change to a container, such as
push_back, makes existing iterators, references or pointers into it unusable.
The same loops come up again and again: count the G and C bases in a sequence, find the best read, sort the reads by quality, add up a column of numbers. Writing each one by hand takes time and invites off-by-one mistakes. The standard library has named, tested versions of all of them, called algorithms. They work on any container through iterators, and a lambda fills in the details.
In 30 seconds
- An iterator marks a position in a container.
begin()is the first element;end()is one past the last. - Algorithms from
<algorithm>and<numeric>take a pair of iterators:std::sort(v.begin(), v.end()). - The
std::ranges::versions take the whole container and a projection:std::ranges::sort(reads, {}, &Read::quality). - Don’t add or remove elements while you loop over a container: the iterators you’re using can stop being valid.
Iterators: positions in a container
An iterator works like a pointer to an element. *it reads the element it points at, ++it moves to the next one, and two iterators compare equal when they’re at the same position. Every standard container has begin() and end():
#include <print>
#include <string>
std::string seq = "GATC";
for (auto it = seq.begin(); it != seq.end(); ++it) {
std::print("{} ", *it);
}
std::println("");Output
G A T C
A range-based for loop is this loop written for you: it calls begin() and end() and walks from one to the other.
Half-open ranges
end() doesn’t point at the last element. It points one past it, at the position where the elements stop. A pair of iterators like this, written [begin, end), is a half-open range: the [ means the first position is included, the ) means the last isn’t.
| Iterator | Position | Element | *it allowed? |
|---|---|---|---|
seq.begin() | 0 | G | yes |
seq.begin() + 1 | 1 | A | yes |
seq.begin() + 3 | 3 | C | yes |
seq.end() | 4 | none: past the end | no |
This choice makes the common cases easy. For a string or a vector, the number of elements is end - begin. An empty container has begin() == end(), so the loop above runs zero times with no special case. And “not found” has an obvious answer: return end().
#include <print>
#include <string>
std::string seq = "GATC";
std::string empty;
std::println("{} {}", seq.end() - seq.begin(), seq.size());
std::println("{}", empty.begin() == empty.end());Output
4 4 true
Finding and counting
std::find(first, last, value) returns an iterator to the first element equal to value, or last if there’s none. Always compare the result with end() before you use it:
#include <algorithm>
#include <print>
#include <string>
std::string seq = "GATTNACA";
auto it = std::find(seq.begin(), seq.end(), 'N');
if (it != seq.end()) {
std::println("unknown base at position {}", it - seq.begin());
}Output
unknown base at position 4
std::count counts elements equal to a value. std::count_if counts the elements for which a predicate returns true, which makes GC content a one-liner:
#include <algorithm>
#include <print>
#include <string>
std::string seq = "GATTACAGGC";
auto gc = std::count_if(seq.begin(), seq.end(), [](char base) {
return base == 'G' || base == 'C';
});
auto t = std::count(seq.begin(), seq.end(), 'T');
std::println("G or C: {}, T: {}", gc, t);
std::println("GC content: {}",
static_cast<double>(gc) / static_cast<double>(seq.size()));Output
G or C: 5, T: 2 GC content: 0.5
Sorting
std::sort(first, last) puts the elements in order, smallest first, using <. To choose a different order, pass a comparator as a third argument: a function that returns true when its first argument should come first. std::greater<>(), from <functional>, sorts largest first:
#include <algorithm>
#include <functional>
#include <print>
#include <vector>
std::vector<int> qualities = {38, 12, 40, 9, 33};
std::sort(qualities.begin(), qualities.end());
std::println("{}", qualities);
std::sort(qualities.begin(), qualities.end(), std::greater<>());
std::println("{}", qualities);Output
[9, 12, 33, 38, 40] [40, 38, 33, 12, 9]
For your own types, a lambda comparator says which member to compare. Here reads are sorted by quality, best first:
#include <algorithm>
#include <print>
#include <string>
#include <vector>
struct Read {
std::string id;
int quality;
};
int main() {
std::vector<Read> reads = {{"r1", 31}, {"r2", 12}, {"r3", 38}, {"r4", 25}};
std::sort(reads.begin(), reads.end(), [](const Read& a, const Read& b) {
return a.quality > b.quality;
});
for (const auto& r : reads) {
std::print("{}:{} ", r.id, r.quality);
}
std::println("");
}Output
r3:38 r1:31 r4:25 r2:12
Common pitfallstd::sort doesn't keep ties in order
When two elements compare equal, std::sort may put them in either order. If reads with the same quality must stay in their original order, use std::stable_sort, which takes the same arguments.
Smallest and largest
std::min_element and std::max_element return an iterator to the smallest or largest element, not the value. That tells you where it is, too. On an empty range they return last, so check before using *:
#include <algorithm>
#include <print>
#include <vector>
std::vector<int> qualities = {38, 12, 40, 9, 33};
auto lowest = std::min_element(qualities.begin(), qualities.end());
auto highest = std::max_element(qualities.begin(), qualities.end());
std::println("min {} at {}", *lowest, lowest - qualities.begin());
std::println("max {} at {}", *highest, highest - qualities.begin());Output
min 9 at 3 max 40 at 2
Transforming every element
std::transform(first, last, out, f) calls f on each element and writes the results starting at out. Here Phred quality scores become error probabilities, 10 to the power of minus quality / 10. The output vector must already have room for every result:
#include <algorithm>
#include <cmath>
#include <print>
#include <vector>
std::vector<int> qualities = {20, 30, 10};
std::vector<double> error_rates(qualities.size());
std::transform(qualities.begin(), qualities.end(), error_rates.begin(),
[](int q) { return std::pow(10.0, -q / 10.0); });
std::println("{}", error_rates);Output
[0.01, 0.001, 0.1]
out can be the start of the input itself, which changes the elements in place. This turns a DNA sequence into its complement:
#include <algorithm>
#include <print>
#include <string>
std::string seq = "GATTACA";
std::transform(seq.begin(), seq.end(), seq.begin(), [](char base) {
switch (base) {
case 'A':
return 'T';
case 'T':
return 'A';
case 'G':
return 'C';
default:
return 'G';
}
});
std::println("{}", seq);Output
CTAATGT
Adding up: std::accumulate and std::reduce
std::accumulate(first, last, init), from <numeric>, starts with init and adds each element to it. std::reduce(first, last) adds them too, but the standard lets it add in any order and group the additions however it likes, so the work can be split up (Module 10 does that across threads). With no init, it starts from zero of the element type:
#include <numeric>
#include <print>
#include <vector>
std::vector<double> means = {31.5, 28.25, 35.75};
double total = std::accumulate(means.begin(), means.end(), 0.0);
std::println("{}", total);
std::println("{}", std::reduce(means.begin(), means.end()));Output
95.5 95.5
Because floating-point rounding depends on the order of additions, std::reduce on doubles can give a slightly different last digit from std::accumulate on large inputs. For integers, the result is the same.
The std::ranges:: versions and projections
Passing v.begin(), v.end() every time is noisy, and it’s easy to pass iterators from two different containers by mistake. Since C++20, most algorithms in <algorithm> also have a version in std::ranges:: that takes the container itself:
#include <algorithm>
#include <print>
#include <vector>
std::vector<int> qualities = {38, 12, 40, 9, 33};
std::ranges::sort(qualities);
auto good = std::ranges::count_if(qualities, [](int q) { return q >= 30; });
std::println("{} {}", qualities, good);Output
[9, 12, 33, 38, 40] 3
They also take a projection: a function applied to each element before it’s compared or tested. &Read::quality is a pointer to member; as a projection it means “use the quality of each read”. The {} before it keeps the default comparison, smallest first; std::ranges::greater() sorts largest first:
#include <algorithm>
#include <functional>
#include <print>
#include <string>
#include <vector>
struct Read {
std::string id;
int quality;
};
int main() {
std::vector<Read> reads = {{"r1", 31}, {"r2", 12}, {"r3", 38}, {"r4", 25}};
auto best = std::ranges::max_element(reads, {}, &Read::quality);
std::println("best: {} ({})", best->id, best->quality);
std::ranges::sort(reads, std::ranges::greater(), &Read::quality);
for (const auto& r : reads) {
std::print("{} ", r.id);
}
std::println("");
}Output
best: r3 (38) r3 r1 r4 r2
best is an iterator, so best->id reads a member of the element it points at, the same -> as for pointers. The projection says what to compare; you don’t need a two-argument lambda.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
A std::ranges:: algorithm | Whenever an algorithm fits and you’re working on a whole container. | Shorter, can’t mix up iterators, and projections replace most comparators. | std::ranges::sort(reads, {}, &Read::quality) |
A classic algorithm (std::sort(b, e)) | Part of a container, code that must build as C++17, and std::accumulate and std::reduce, which have no std::ranges:: version (C++23’s std::ranges::fold_left is the nearest to accumulate). | Works on any pair of iterators. | std::accumulate(v.begin(), v.end(), 0.0) |
std::reduce | Adding up many numbers where the order of additions doesn’t matter. | It may group the additions, which allows splitting the work. | std::reduce(v.begin(), v.end()) |
| A hand-written loop | No algorithm says what you mean, or one pass computes several results at once. | Clearer than forcing an algorithm that doesn’t fit. | for (const auto& r : reads) { … } |
Rule of thumb: if you can name what a loop does (find, count, sort, sum), there’s an algorithm with that name. Use the std::ranges:: version when there is one.
Under the hood
An algorithm is a function template. std::sort doesn’t know about std::vector; it uses only what iterators offer: *, ++, comparing, and for sorting, jumping with it + n. The compiler writes a version for the exact iterator type, so the result runs about as fast as a loop you’d write by hand.
With GCC’s standard library, the iterator of a std::vector, std::string or std::array is a pointer to the element, or a thin wrapper around one: 8 bytes on this platform. A plain pointer supports *, ++ and + n as well, so it works as an iterator too, and algorithms run on C arrays:
#include <algorithm>
#include <print>
#include <vector>
int counts[] = {7, 3, 9, 1};
std::sort(counts, counts + 4);
std::println("{} {} {} {}", counts[0], counts[1], counts[2], counts[3]);
std::println("{}", sizeof(std::vector<int>::iterator));Output
1 3 7 9 8
Not every iterator can jump. A std::list, from <list>, stores each element in its own heap block linked to its neighbors, so its iterator can only step one element at a time, forward or back. Iterators that can jump any distance at once are called random-access iterators; std::sort needs them, and that’s what goes wrong in the last pitfall below. std::find, std::count_if and std::accumulate only step forward, so they work on any container.
Common pitfalls
0 instead of 0.0 in std::accumulate
The result of std::accumulate has the type of init. With 0, an int, every partial sum is converted back to int, and the fraction is cut off at each step:
#include <numeric>
#include <print>
#include <vector>
std::vector<double> means = {31.5, 28.25, 35.75};
auto wrong = std::accumulate(means.begin(), means.end(), 0);
auto right = std::accumulate(means.begin(), means.end(), 0.0);
std::println("{} {}", wrong, right);Output
94 95.5
The compiler accepts this without a warning: the conversion happens inside the standard library. 0 + 31.5 becomes 31, 31 + 28.25 becomes 59, and 59 + 35.75 becomes 94. Write 0.0 for doubles, and std::int64_t{0} when an int total could overflow.
Changing a vector while looping over it
A range-based for holds iterators into the vector. When push_back needs more room, the vector moves its elements to a bigger block and frees the old one (vector lists the rules), so the loop’s iterators point into freed memory. Even when there’s room, push_back invalidates end(), which the loop compares against, so the loop is wrong either way:
#include <print>
#include <vector>
std::vector<int> qualities = {30, 12, 40};
for (int q : qualities) {
if (q < 20) {
qualities.push_back(20); // invalidates the loop's iterators
}
}
std::println("{}", qualities);This fails when it runs
ERROR: AddressSanitizer: heap-use-after-free on address 0x…
READ of size 4 at 0x… thread T0
#0 main main.cpp:5
0x… is located 8 bytes inside of 12-byte region [0x…,0x…)
freed by thread T0 here:
#0 operator delete(void*, unsigned long)
… 8 frames inside the standard library
#9 main main.cpp:7
previously allocated by thread T0 here:
#0 operator new(unsigned long)
… 6 frames inside the standard library
#7 main main.cpp:4
SUMMARY: AddressSanitizer: heap-use-after-free main.cpp:5 in mainCollect the new elements in a separate vector and add them after the loop. To remove elements, don’t erase inside a loop; use std::erase_if(qualities, predicate) (see vector).
#include <print>
#include <vector>
std::vector<int> qualities = {30, 12, 40};
std::vector<int> extra;
for (int q : qualities) {
if (q < 20) {
extra.push_back(20);
}
}
qualities.insert(qualities.end(), extra.begin(), extra.end());
std::println("{}", qualities);Output
[30, 12, 40, 20]
Sorting a container without random-access iterators
std::list iterators can’t jump, so std::ranges::sort refuses a list. The error is long, because it comes from a template inside the standard library. Read the error: line first, then look further down for constraints not satisfied and the requirement that failed, random_access_range:
#include <algorithm>
#include <list>
int main() {
std::list<int> qualities = {38, 12, 40};
std::ranges::sort(qualities);
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:6:22: error: no match for call to ‘(const std::ranges::__sort_fn) (std::__cxx11::list<int>&)’
6 | std::ranges::sort(qualities);
| ~~~~~~~~~~~~~~~~~^~~~~~~~~~~
In file included from /usr/include/c++/15/algorithm:65,
from main.cpp:1:
/usr/include/c++/15/bits/ranges_algo.h:1812:10: note: there are 2 candidates
| struct __sort_fn
| ^~~~~~~~~
/usr/include/c++/15/bits/ranges_algo.h:1818:7: note: candidate 1: ‘template<class _Iter, class _Sent, class _Comp, class _Proj> requires (random_access_iterator<_Iter>) && (sentinel_for<_Sent, _Iter>) && (sortable<_Iter, _Comp, _Proj>) constexpr _Iter std::ranges::__sort_fn::operator()(_Iter, _Sent, _Comp, _Proj) const’
| operator()(_Iter __first, _Sent __last,
| ^~~~~~~~
/usr/include/c++/15/bits/ranges_algo.h:1818:7: note: candidate expects 2 arguments, 1 provided
/usr/include/c++/15/bits/ranges_algo.h:1831:7: note: candidate 2: ‘template<class _Range, class _Comp, class _Proj> requires (random_access_range<_Range>) && (sortable<decltype(std::ranges::__access::__begin((declval<_Container&>)())), _Comp, _Proj>) constexpr std::ranges::borrowed_iterator_t<_Range> std::ranges::__sort_fn::operator()(_Range&&, _Comp, _Proj) const’
| operator()(_Range&& __r, _Comp __comp = {}, _Proj __proj = {}) const
| ^~~~~~~~
/usr/include/c++/15/bits/ranges_algo.h:1831:7: note: template argument deduction/substitution failed:
/usr/include/c++/15/bits/ranges_algo.h:1831:7: note: constraints not satisfied
In file included from /usr/include/c++/15/compare:42,
from /usr/include/c++/15/bits/stl_pair.h:65,
from /usr/include/c++/15/bits/stl_algobase.h:64,
from /usr/include/c++/15/algorithm:62:
/usr/include/c++/15/concepts: In substitution of ‘template<class _Range, class _Comp, class _Proj> requires (random_access_range<_Range>) && (sortable<decltype(std::ranges::__access::__begin((declval<_Container&>)())), _Comp, _Proj>) constexpr std::ranges::borrowed_iterator_t<_Range> std::ranges::__sort_fn::operator()(_Range&&, _Comp, _Proj) const [with _Range = std::__cxx11::list<int>&; _Comp = std::ranges::less; _Proj = std::identity]’:
main.cpp:6:22: required from here
6 | std::ranges::sort(qualities);
| ~~~~~~~~~~~~~~~~~^~~~~~~~~~~
/usr/include/c++/15/concepts:76:13: required for the satisfaction of ‘derived_from<typename std::__detail::__iter_concept_impl<_Iter>::type, std::random_access_iterator_tag>’ [with _Iter = std::_List_iterator<int>]
/usr/include/c++/15/bits/iterator_concepts.h:719:13: required for the satisfaction of ‘random_access_iterator<decltype (std::ranges::__access::__begin(declval<_Container&>()))>’ [with _Tp = std::__cxx11::list<int, std::allocator<int> >&]
/usr/include/c++/15/bits/ranges_base.h:619:13: required for the satisfaction of ‘random_access_range<_Range>’ [with _Range = std::__cxx11::list<int, std::allocator<int> >&]
/usr/include/c++/15/concepts:76:28: note: ‘std::random_access_iterator_tag’ is not a base of ‘std::bidirectional_iterator_tag’
| concept derived_from = __is_base_of(_Base, _Derived)
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~A list has its own sort member function, qualities.sort(). Usually the better fix is to store the data in a std::vector.
Try it yourself
Try it yourself
This program finds the best read and counts the reads with quality 30 or more, using two hand-written loops. Replace each loop with one std::ranges:: algorithm and a projection. The output should stay the same.
#include <print>
#include <string>
#include <vector>
struct Read {
std::string id;
int quality;
};
int main() {
std::vector<Read> reads = {{"r1", 31}, {"r2", 12}, {"r3", 38}, {"r4", 25}};
const Read* best = &reads[0];
for (const auto& r : reads) {
if (r.quality > best->quality) {
best = &r;
}
}
int good = 0;
for (const auto& r : reads) {
if (r.quality >= 30) {
++good;
}
}
std::println("best: {}, good: {}", best->id, good);
}Expected output
best: r3, good: 2
Show a hint
std::ranges::max_element(reads, {}, &Read::quality) returns an iterator to the best read. std::ranges::count_if(reads, predicate, &Read::quality) passes each read's quality to the predicate.
Show a solution
#include <algorithm>
#include <print>
#include <string>
#include <vector>
struct Read {
std::string id;
int quality;
};
int main() {
std::vector<Read> reads = {{"r1", 31}, {"r2", 12}, {"r3", 38}, {"r4", 25}};
auto best = std::ranges::max_element(reads, {}, &Read::quality);
auto good = std::ranges::count_if(
reads, [](int q) { return q >= 30; }, &Read::quality);
std::println("best: {}, good: {}", best->id, good);
}The projection &Read::quality makes both algorithms look at the quality of each read, so max_element needs no comparator and the count_if predicate takes an int. max_element returns an iterator, and best->id reads the id of the read it points at.
Saved in this browser only.