2.1.4 Looping Through a Vector

You can loop through a vector similar to how you loop through lists in other languages. The two most common methods are for loops and for-each loops.

For Loop:

for(int i = 0; i < myVector.size(); i++) {...}

For-Each Loop:

for(type item : myVector) {...}

For Loop

Vectors have a size function that allows us to loop over the entire vector. Size returns the number of values, so the indices will go from 0 to size - 1. Inside the loop, you access each element by its index.

vector<char> v {'E', 'a', 'g', 'l', 'e'};

for (int i = 0; i < v.size(); i++) {
    cout << i << ": " << v[i] << endl;
}

Output:

0: E
1: a
2: g
3: l
4: e

For-Each Loop

For-each loops allow us to access each element in order, but we do not have a counter variable to use as reference. Notice the name is for-each, but the loop still only uses the for keyword.

vector<char> v {'E', 'a', 'g', 'l', 'e'};

for (char letter : v) {
    cout << letter << endl;
} 

Output:

E
a
g
l
e

In this loop, the variable letter takes on a new value each time through the loop. The first time it is an E, then takes the a next time through and continues until the end.

Last updated