Looping over a Vector
Loops and vectors belong together. A for loop can go through the indexes of a vector, from 0 to the last one, and read each element:
std::vector<std::string> games = {"Football", "Tennis", "Golf"};
for (int i = 0; i < games.size(); i++) {
std::cout << games[i] << std::endl;
}This prints:
Football
Tennis
GolfThe variable i takes the values 0, 1 and 2, and games[i] is the element at that index. The condition uses <, not <=. The vector has 3 elements, so its last index is games.size() - 1, which is 2. With <=, the loop would also read games[3], an element that doesn't exist, and the program would print garbage or crash. With games.at(i) instead of games[i], it would stop with an error.
Going through all the elements is so common that C++ has a shorter way to write it, the range-based for loop:
std::vector<std::string> games = {"Football", "Tennis", "Golf"};
for (std::string game : games) {
std::cout << game << std::endl;
}Football
Tennis
GolfRead it as “for each game in games”. In each iteration, the variable game holds the next element: first "Football", then "Tennis" and then "Golf". After the last element, the loop ends. You don't need an index or size() at all, so you can't get them wrong either.
Before the colon, you create the variable for the elements. Its type must be the type of the elements: std::string for a std::vector<std::string>, int for a std::vector<int>. With the wrong type, for example for (int game : games), Clang reports error: no viable conversion from 'std::string' to 'int'. The name is up to you. A good habit is to name the variable after one element: game in games, price in prices.
Which loop should you use? The range-based for when you just need each element. The loop with an index when you need the index itself, for example to number the elements, or when you want to change the elements. In the range-based loop, the variable holds a copy of the element, so changing it doesn't change the vector. Through the index, you change the element itself:
std::vector<int> numbers = {1, 2, 3};
for (int i = 0; i < numbers.size(); i++) {
numbers[i] = numbers[i] * 10;
}
for (int number : numbers) {
std::cout << number << std::endl;
}10
20
30Instructions
- 1
Below the line that prints the number of teammates, write a range-based
forloop over the vectorteammates. - 2
In the loop, print each teammate on its own line:
Andrew,Thomas,JohnandPaul. - 3
Below it, write a loop with an index that prints the teammates with their numbers:
1. Andrew,2. Thomas,3. Johnand4. Paul, each on its own line. The number is one more than the index,i + 1.