ZetCode

C++ foreach

last modified January 9, 2023

C++ foreach tutorial shows how to loop over containers in C++.

C++ 11 introduced range-based for loop. The for-range loop can be used to easily loop over elements of containers, including arrays, vectors, lists, and maps.

C++ foreach array

An array is a fixed-size sequential collection of elements of the same type.

foreach_array.cpp
#include <iostream>

int main() {

    int vals[] {1, 2, 3, 4, 5};

    for (auto val : vals) {

        std::cout << val << std::endl;
    }
}

The example prints all elements of the array of integers.

$ ./foreach_array 
1
2
3
4
5

C++ foreach vector

A vector is a dynamic array.

foreach_vector.cpp
#include <iostream>
#include <vector>

int main() {

    std::vector<int> nums { 1, 2, 3, 4, 5, 6, 7 };

    for (auto num: nums) {

        std::cout << num << std::endl;
    }
}

We go over the vector of integers.

$ ./foreach_vector 
1
2
3
4
5
6
7

C++ foreach list

A list is a container which supports constant time insertion and removal of elements from anywhere in the container. It allows non-contiguous memory allocations.

foreach_list.cpp
#include <iostream>
#include <list>

int main() {

    std::list<std::string> words = { "falcon", "sky", "cloud", "book" };

    for (auto word: words) {

        std::cout << word << std::endl;
    }
}

We print all elements of the list of strings.

$ ./foreach_list 
falcon
sky
cloud
book

C++ foreach map

A map is a container which stores key/value pairs.

foreach_map.cpp
#include <iostream>
#include <map>

int main() {

    std::map<std::string, int> items {
        {"coins", 3},
        {"pens", 2},
        {"keys", 1},
        {"sheets", 12}
    };

    for (auto item: items) {

        std::cout << item.first << ": " << item.second << std::endl;
    }
}

We have a map of domains. Using the for-range loop we go over the key/value pairs of the map.

$ ./foreach_map 
coins: 3
keys: 1
pens: 2
sheets: 12

In this article, we have worked with for-range loop in C++.