Skip to main content

Section 13.7 Traversing vectors

Many computations can be implemented by looping through the elements of an vector and performing an operation on each element. Looping through the elements of an vector is called a traversal:
Listing 13.7.1.
You will notice that the traversal looks just like looping through the characters of a string. We use a variable of type size_t to track our position. And we use .size() to determine where to stop. Of course, we can do things other than print the elements. This example traverses an vector and squares each element:
Listing 13.7.2.
Also, similar to when iterating through the characters in a string, we can use a range-based loop to iterate through vectors. If we don’t care about knowing the index of each item, this syntax can simplify things:
Listing 13.7.3.
Note that the local variable used to hold the current element during each iteration of the loop has the type of data that the vector is storing. For a vector<int> we use for (int NAME : ... while for a vector<string> we say for (string NAME : ....
It is also possible to use a range-based loop to modify elements in a vector. To do so, we have to use a reference to the current item. By declaring the type as int& we can avoid copying the value of each element into the loop variable. Instead, the loop variable will be an alias for the current element.
Listing 13.7.4.
Note that on line 7 we have for (int& value : a) because it needs to modify the elements in the vector a. The second loop does not need (or want) to modify anything, so it just uses for (int value : a). Try modifying line 7 to use use for (int value : a). If you do so, you will notice that items in the vector are not modified. This is because value is now getting a copy of the current element. Changing that copy does not affect the original.

Insight 13.7.1.

The rules for when to use references in a range-based loop are the same as for functions:
  • If you do not need to modify the elements and the are small (like an int or double), use a regular variable (e.g., int).
  • If you need to modify the elements of the vector, use a reference (e.g., int&).
  • If you do not need to modify the elements, and they are large (like long strings or other complex data), use a reference to const (e.g., const string&). You can use a regular variable in this case, but it will be less efficient because of all of the copying.

Checkpoint 13.7.1.

Construct a block of code that loops over a vector called numbers and transforms the vector so each element is doubled.

Checkpoint 13.7.2.

Suppose you have the vector vector<string> words = {"car", "cat", "switch", "alpha"}. Construct a block of code that makes each word upper case and results in the vector to vector<string> words = {"Car", "Cat", "Switch", "Alpha"}
You have attempted of activities on this page.