Looping Over Vectors: range-based for

Looping with an index works, but C++ has a shorter way to say “for each item in the vector”:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    vector<string> fruits = {"apple", "banana", "cherry"};
    for (string fruit : fruits) {
        cout << "I like " << fruit << "\n";
    }
    return 0;
}

Output

I like apple
I like banana
I like cherry

Read for (string fruit : fruits) as: “for each fruit in fruits”.

Changing the items: use &

The loop variable is a copy. To change the real items, make it a reference with &:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> prices = {10, 25, 40};
    for (int& price : prices) {
        price *= 2;                // doubles the real items
    }
    for (int price : prices) {
        cout << price << " ";
    }
    cout << "\n";
    return 0;
}

Output

20 50 80 

Tip: Use auto to save typing: for (auto& x : v) or for (const auto& x : v).

Remember: Need the position number too? Use a normal for loop with an index. Only need the items? The range-based for is shorter and safer.

2D vectors: a grid

A vector can hold other vectors. That gives you rows and columns, like a table or a game board:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<vector<int>> grid = {
        {1, 2, 3},
        {4, 5, 6},
    };
    cout << "Row 1, column 2: " << grid[1][2] << "\n";
    for (const auto& row : grid) {
        for (int cell : row) {
            cout << cell << " ";
        }
        cout << "\n";
    }
    return 0;
}

Output

Row 1, column 2: 6
1 2 3 
4 5 6 
HOME LABS COMMUNITY DASHBOARD