Range-Based For Loop with an example

Range-Based For Loop with an example

Introduced in C++11, the range-based for loop provides a clean, readable syntax to iterate over elements in containers like arrays, vectors, maps, sets, etc.

It eliminates the need for manual indexing or iterator usage.

๐Ÿ”น Basic Syntax

for (declaration : container) {
    // use declaration
}

๐Ÿ”ธ Example 1: Loop Over std::vector

#include <vector>
#include <iostream>

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5};

    for (int n : nums) {
        std::cout << n << " ";
    }
    // Output: 1 2 3 4 5
}

๐Ÿ”ธ Example 2: With References (Modify Elements)

for (int& n : nums) {
    n *= 2;
}

๐Ÿ”น Without &, you get a copy, and changes won’t affect the original container.

๐Ÿ”ธ Example 3: With const Reference (Best for Read-Only)

for (const std::string& s : names) {
    std::cout << s << "\n";
}

โœ… Use const & when:

  • You’re only reading
  • Container holds large objects (like std::string, std::vector)

๐Ÿ”ธ Example 4: Looping Over Array

int arr[] = {10, 20, 30};
for (int x : arr) {
    std::cout << x << "\n";
}

C++17 Enhancement: Structured Bindings

๐Ÿ”ธ Example 5: Loop Over Map

std::map<std::string, int> ages = {{"Alice", 30}, {"Bob", 25}};
for (const auto& pair : ages) {
    std::cout << pair.first << " = " << pair.second << "\n";
}

C++17 Enhancement:

for (const auto& [name, age] : ages) {
    std::cout << name << " is " << age << "\n";
}