2 Containers, iterators, and ranges

 

This chapter covers

  • Filling and using containers, with a 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 have included sequences (e.g., vector), associative containers (e.g., map), and, since C++ 11, unordered associative containers (e.g., unordered_map). The containers manage the storage for their elements. The separation of data structures and algorithms offers great flexibility, allowing one algorithm to be applied to various containers. The addition of ranges to the core language provides simplified ways to access and manipulate containers. To explore these features, in this chapter, we are going to construct Pascal’s triangle, which is made by adding up adjacent numbers from the preceding row, starting with a single 1 in the first row. The entries can be used to count the number of event combinations and more. We will use vectors to store the values, starting with the first row, to practice using a vector and writing out to the screen. We’ll then generate and display more rows, learning how to use vectors differently. Finally, we’ll discuss some of the triangle’s properties. This will help us think about testing our code later.

2.1 Creating and displaying a vector

2.2 Creating and displaying Pascal’s triangle

2.2.1 A reminder of Pascal’s triangle

2.2.2 Coding Pascal’s triangle

2.2.3 Move semantics and perfect forwarding

2.2.4 Using ranges to display the vector

2.2.5 Using format to display output

2.3 Properties of the triangle

2.3.1 Checking the first and last elements of each row

2.3.2 Checking the number of elements in each row

2.3.3 Checking the sum of the elements in a row

2.3.4 How many rows can we generate correctly?