C++ How To Loop Through a Vector
Loop Through a Vector
Use a for-each loop to go through all the elements of a vector:
Example
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (string car : cars) {
cout << car << "\n";
}
If you also need the position of each element, use a regular for loop with size():
Example
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.size(); i++) {
cout << i << ": " << cars[i] << "\n";
}
Explanation:
The for-each loop gives you each element, one by one.
The regular loop uses i as the position, from 0 up to cars.size() - 1.