C++ · Module 4 · Lesson 61 min read

Range-based for Loops

Syntax (C++11)

c
for (declaration : range) { ... }

std::vector<int> scores = { 80, 92, 75 };
for (int s : scores) std::cout << s << ' ';

Works with arrays, std::vector, std::string, std::map, initializer lists {1, 2, 3} and anything with begin()/end().

Copy vs reference — choose carefully

FormUse when
for (auto x : v)small types (int, double, char); you get a copy
for (const auto& x : v) ✅read large objects (strings, structs) without copying
for (auto& x : v)modify the elements in place
less
for (auto& price : prices) price *= 1.13;   // add VAT to every price

With an initializer (C++20)

c
for (int i = 0; const auto& name : names) {
    std::cout << ++i << ". " << name << '\n';
}

Gives you a counter without a classic for loop.

Structured bindings with maps (C++17)

arduino
for (const auto& [category, amount] : budget) { ... }

When you still need a classic for

  • You need the index (or use the C++20 initializer trick)
  • Iterating backwards or skipping elements
  • Changing the container's size while looping ⚠️ (never add/remove elements in a range-for over the same container)

Under the hood

The compiler rewrites it as a loop using iterators begin() and end() — just as fast as a hand-written loop.

Example

C++
#include <iostream>
#include <map>
#include <string>
#include <vector>

int main() {
    std::vector<double> prices = { 100, 250, 1500 };
    for (auto& p : prices) p *= 1.13;                 // reference: modify in place
    for (double p : prices) std::cout << p << ' ';    // copy: fine for doubles
    std::cout << '\n';

    std::vector<std::string> friends = { "Asha", "Ravi", "Sita" };
    for (int i = 0; const auto& name : friends)       // C++20 range-for with initializer
        std::cout << ++i << ". " << name << '\n';

    std::string word = "budget";
    int vowels = 0;
    for (char c : word)
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') ++vowels;
    std::cout << word << " has " << vowels << " vowels\n";

    std::map<std::string, int> spending = { {"Food", 4200}, {"Rent", 15000}, {"Travel", 1800} };
    int total = 0;
    for (const auto& [category, amount] : spending) {   // structured bindings
        std::cout << category << ": " << amount << '\n';
        total += amount;
    }
    std::cout << "Total: " << total << '\n';

    for (int n : { 2, 3, 5, 7 }) std::cout << n * n << ' ';
    std::cout << '\n';
    return 0;
}

/* Output:
113 282.5 1695
1. Asha
2. Ravi
3. Sita
budget has 2 vowels
Food: 4200
Rent: 15000
Travel: 1800
Total: 21000
4 9 25 49
*/