Iterators, algorithms and the standard library

Positions instead of indices, half-open ranges, sorting, spans, random numbers and reading files.

What you'll learn
  • Walk a container with begin, end, rbegin and rend
  • Explain why end() points one past the last element
  • Use std::ranges::sort, std::span, and file streams

An iterator is a position in a container. *itr reads the element there, and itr += 1 moves to the next. Every standard algorithm is written against iterators, which is why one std::sort works for arrays, vectors and deques alike.

The three loops of 09iterators.cpp. end() and rend() are positions just outside the array; the loop stops when the iterator reaches them and never dereferences them.

09iterators.cpp runs the same loop three ways:

for (auto itr = my_array.begin(); itr < my_array.end(); itr += 1)       // 1 2 3 4 5
for (auto itr = my_array.begin() + 2; itr < my_array.end(); itr += 1)   // 3 4 5
for (auto itr = my_array.rbegin(); itr < my_array.rend(); itr += 1)     // 5 4 3 2 1

The range is half-open: [begin, end). end() is one past the last element, so an empty container has begin() == end(), and the number of elements is simply end() - begin(). A reverse iterator is the same idea seen from the other side: rbegin() sits on the last element, rend() just before the first, and += 1 moves backwards through memory.

The < comparison works here because array iterators are random-access. The idiomatic test, which works for every container including std::list, is itr != my_array.end().

Sorting

std::sort(my_array.begin(), my_array.end());   // iterator pair
std::ranges::sort(my_array);                   // C++20: the whole range

10sort.cpp turns 53 21 3 4 98 into 3 4 21 53 98. The iterator form can sort just a part — std::sort(my_array.begin() + 1, my_array.end()).

Spans

std::span<int> (17span.cpp) is a non-owning view: a pointer plus a length. A function taking a span accepts arrays, vectors or a slice of either without copying:

print_subvector(my_vector);                              // 1 2 3 4 5
print_subvector(std::span(my_vector.begin(), 2));        // 1 2
print_subvector(std::span(my_vector.begin() + 1, 3));    // 2 3 4

Because a span does not own anything, it must not outlive the container it looks into — the same rule as for the references of lesson 5.

Random numbers and files

37random_numbers.cpp separates the two jobs rand() mixes together: std::random_device provides real entropy, std::mt19937 is a fast, reproducible generator seeded from it, and a distribution shapes the output — std::uniform_int_distribution uniform(1, 6) rolls a die. Seed the generator with a fixed number instead of rd() and every run gives the same sequence, which is what tests and simulations want.

38file_io.cpp reads integers with while (input >> data), a loop that stops on end of file or on the first value that is not a number. The repository does not include its data.txt, so as checked in the folder it prints an empty line: the open fails silently. Testing if (!input) after opening would say so.

Try it yourself. Use std::ranges::find_if to find the first even number in {53, 21, 3, 4, 98}, and print its index using itr - my_array.begin(). What does find_if return when nothing matches, and why must you check before dereferencing it?

View source on GitHub →