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 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.
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.
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.
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"}