Vector Iteration
Sometimes we want to go through vector elements one by one. We can achieve this in several ways using a for loop.
A classic for
loop could look as follows:
std::vector games = {"Football", "Tennis", "Golf"};
for (int i = 0; i < games.size(); i++) {
std::cout << games[i] << std::endl;
}
Prints:
Football
Tennis
Golf
This loop repeats as long as i
is less than the size of the vector and in each iteration prints the vector element at index i
.
In C++ we also have a more modern and simpler way to achieve this - range-based for loop:
std::vector<std::string> games = {"Football", "Tennis", "Golf"};
for (std::string element : games) {
std::cout << element << std::endl;
}
Prints:
Football
Tennis
Golf
Here we have iterator variable element
(we can give it any name). This notation stores the value of the corresponding vector element into variable element
in each iteration.
The disadvantage of this notation is that it can only be used when we want to go through all vector elements. With the standard notation we can also go backwards, skip elements or start at a chosen index.
Instructions
Using any notation of the for
loop, go through the vector teammates
and print each vector element on a new line.
Start programming for free
4/9