← Patterns

Range iteration

1234567891011121314#include <vector> int main() { int arr[] = {1, 2, 3, 4, 5}; for (int value : arr) { // Use value } std::vector<int> vec = {1, 2, 3, 4, 5}; for (int& ref : vec) { // Modify ref } }

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++11 or newer.

Intent

Iterate over a range of elements without using iterators or indices.

Description

The range-based for loop provides a simple syntax for iterating over elements of a range without using iterators or indices. It supports arrays, types that provide begin and end member functions, and types for which begin and end functions are found via argument-dependent lookup.

Lines 6–8 demonstrate iterating over an array, arr. In each iteration, value will have the value of each successive element of arr.

Lines 11–13 similarly demonstrate iterating over a std::vector, vec (any standard container will also work). In this case, we have defined ref as a reference type, which will allow us to modify the objects stored in vec.

Contributors

  • Joseph Mansfield

Last Updated

09 December 2017

Source

Fork this pattern on GitHub

Share