Chapter 5. The Standard Template Library Part II: Algorithms and Ranges

The preceding chapter covered STL containers, including std::vector, std::deque, and std::map, as well as how iterators on these containers work. In this chapter, you will see how STL algorithms are used to traverse an STL container, apply a function to each member, and replace iterative loops with a single statement, resulting in more-efficient and safer code. Because algorithms are expressed in terms of iterators, not in terms of containers, you can employ a single algorithm and leverage its impact on a whole set of containers at once.

This chapter also covers ranges, a new feature in the C++20 Standard that makes algorithms more intuitive to work with. The chapter concludes with an introduction to a modern functional approach to C++ programming using range views and range adaptors, also introduced with C++20 but expanded significantly in C++23.

STL Algorithms

STL algorithms, in a single command, can replace operations on sequences of values that would otherwise typically require for or while loop blocks with multiple lines of code. In addition to making code more easily maintainable, they often accomplish the same tasks more efficiently than had they been implemented with handwritten loops, and they clearly indicate user intent, making the code in a sense self-documenting.

Most STL algorithms use a pair of iterators to traverse across the range of a container (or more generally a subset thereof), and many ...

Get Learning Modern C++ for Finance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.