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:
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:
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:
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 possible to use a range-based loop to modify elements in a vector. To do so, we have to make the local variable that stores each element a reference. 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.
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)`. The rules for when to use references in a range-based loop are the same as for functions.
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"}