Module 11 · Iterators: The Thing Between a Container and an Algorithm
When to Use an Iterator, an Index or a Range-for, and When Not To
Free with an accountReading
Bob writes every loop with an index. He does it on a vector, he does it on a list through *next(l.begin(), i), and he walks backwards with a size_t. Some of his loops are fine, but one took more than three seconds for 40,000 numbers, and the test of another can never end it. Amara asks him one question about each loop: what did it need? This lesson is her answer, with a chart, a flowchart, two measurements and one unsigned trap.
Checking what this lesson needs for you…
What is inside When to Use an Iterator, an Index or a Range-for, and When Not To
- Four questions before you write the loop
- The comparison chart
- The decision flowchart
- Summing ten million ints four ways, measured
- An index on a list, measured
- Walking backwards: the size_t trap
- When an index is the clearer tool
- When no loop is needed