2 Containers, iterators, and ranges
This chapter covers
- Filling and using containers, with focus on a vector of numbers.
- Range based for loops and auto.
- Using a container with standard algorithms.
- Using format to display output
- Ranges, views, and lambdas.
Containers and algorithms have been a fundamental part of C++ for a long time. Containers include sequences, such as vector, associative containers, like map, and unordered associative containers (since C++11), like unordered_map. The containers manage storage for their elements. The separation of data structures and algorithms allows great flexibility, allowing one algorithm to be applied to various containers. The addition of ranges to the core language gives simplified ways to access and manipulate containers. To explore these facets, we are going to build up Pascal’s triangle, which is formed by adding adjacent numbers in the previous row, starting with a single 1 in the first row. The entries are useful for counting the number of ways events can be combined, and more besides. We will use vectors to store the values, starting with the first row only to practice using a vector and writing out to the screen. We’ll then generate and display more rows, learning how to use vectors in various ways. Finally, we’ll discuss some of the triangle’s properties. This will help us think about testing our code.