In this C++ tutorial, you will learn how to use the range-based for loop, commonly called a for-each loop, to iterate over arrays, strings, vectors, maps, and other ranges. You will also learn when to use values, references, and const references inside the loop.
C++ for-each loop is a range-based for loop
C++ does not have a foreach keyword. The usual C++ “for-each” syntax is the range-based for loop, introduced in C++11. It visits each element in a range in order and executes the loop body once for that element.
A range-based for loop is useful when you need each element but do not need to manage an index or iterator manually.
Syntax of a C++ for-each loop
The syntax of C++ Foreach statement is given below.
for (int element: arr) {
//statement(s)
}
In this syntax, arr is the range to iterate over, and element receives one element on each iteration. The element type must be compatible with the values stored in the range.
For general-purpose code, auto is often convenient because the compiler deduces the element type.
for (auto element : collection) {
// use element
}
C++ for-each loop with values, references, and const references
The declaration before the colon controls whether each element is copied or accessed directly.
auto elementcopies each element. Changes toelementdo not change the original collection.auto& elementrefers to the original element. Changes made throughelementupdate the collection.const auto& elementrefers to the original element without copying and prevents modification through that reference. This is a common choice for read-only iteration over larger objects.
for (auto& element : collection) {
// element can modify the original item
}
for (const auto& element : collection) {
// read the original item without copying it
}
C++ for-each loop examples with arrays, strings, and vectors
1. C++ for-each loop over an array
In this example, we shall use foreach statement, to find the number of even numbers in an integer array.
C++ Program
#include <iostream>
using namespace std;
int main() {
int nums[] = {4, 9, 6, 72, 31, 44};
int even = 0;
for (int num: nums) {
if (num % 2 == 0)
even++;
}
cout << even;
}
Output
4
The loop examines all six values. The values 4, 6, 72, and 44 are even, so the final count is 4.
2. C++ for-each loop over characters in a string
In this example, we shall use foreach statement, to execute a set of statements for each character in a string.
C++ Program
#include <iostream>
using namespace std;
int main() {
string str = "tutorialkart";
for (char ch: str) {
cout << ch << " ";
}
}
Output
t u t o r i a l k a r t
A std::string can be used directly as the range. On each iteration, ch receives the next character.
In the following program, we shall use foreach statement, to count the number of vowels in a char array.
C++ Program
#include <iostream>
using namespace std;
int main() {
char charArr[] = {'t','u','t','o','r','i','a','l','k','a','r','t'};
int vowels = 0;
for (char ch: charArr) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
}
cout << vowels;
}
Output
5
3. C++ for-each loop over a vector
In the following program, we shall print elements of Vector using Foreach statement.
C++ Program
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums;
nums.push\_back(24);
nums.push\_back(81);
for(int num: nums)
cout << num << " ";
}
Output
24 81
A vector works naturally with a range-based for loop because it provides iterators that define its range. If you only need to read vector elements, you can also write for (const auto& num : nums).
Modify vector elements with a C++ for-each reference
If the loop variable is declared by value, changing it changes only the copy. Use a reference when you want to modify the elements stored in the vector.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {2, 4, 6};
for (int& num : nums) {
num *= 10;
}
for (int num : nums) {
cout << num << " ";
}
}
Output
20 40 60
Here, num is an int&, so it refers to the actual vector element instead of a copy.
C++ for-each loop with an index
A range-based for loop does not provide an index automatically. If you need both the element and its position, maintain a separate index variable or use an indexed for loop.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> names = {"Asha", "Ravi", "Neha"};
size_t index = 0;
for (const auto& name : names) {
cout << index << ": " << name << '\n';
++index;
}
}
Output
0: Asha
1: Ravi
2: Neha
C++ for-each loop over a map
When a range-based for loop iterates over a std::map, each element is a key-value pair. With C++17 structured bindings, you can name the key and value directly.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> scores = {
{"Asha", 92},
{"Ravi", 85}
};
for (const auto& [name, score] : scores) {
cout << name << ": " << score << '\n';
}
}
Output
Asha: 92
Ravi: 85
C++ for-each loop over a two-dimensional array
For a two-dimensional built-in array, use a nested range-based for loop. The outer loop receives each row, and the inner loop receives each element in that row.
#include <iostream>
using namespace std;
int main() {
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for (const auto& row : matrix) {
for (int value : row) {
cout << value << " ";
}
cout << '\n';
}
}
Output
1 2 3
4 5 6
Range-based for loop vs std::for_each in C++
The range-based for loop and std::for_each can both apply work to each element, but they are different language features.
- A range-based
forloop is built into the C++ language and is usually the simplest choice for straightforward iteration. std::for_eachis an algorithm from the standard library. It takes an iterator range and a callable such as a function object or lambda.- Use the form that makes the operation clearest. Other standard algorithms may be a better fit when the task is specifically searching, transforming, counting, or accumulating.
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {3, 6, 9};
for_each(nums.begin(), nums.end(), [](int num) {
cout << num << " ";
});
}
Output
3 6 9
When a C++ for-each loop is the right choice
Use a range-based for loop when your code naturally works with every element in a range. It keeps the loop compact because you do not have to write iterator movement or index bounds.
An indexed for loop is often clearer when the position itself is important, when you need to skip through elements in non-unit steps, or when the algorithm depends on neighboring positions.
Common mistakes in C++ for-each loops
- Expecting changes to persist when iterating by value: use
auto&or an explicit reference type when the original element must be modified. - Copying large objects unnecessarily: prefer
const auto&for read-only access when copying would be wasteful. - Expecting an automatic index: a range-based for loop gives you elements, not their numeric positions.
- Using the Microsoft C++/CLI
for eachextension as if it were standard C++: standard C++ uses the range-basedfor (... : ...)syntax shown in this tutorial. - Trying to use the same syntax in C: the C language does not provide the C++ range-based
forloop.
C++ for-each loop summary
A C++ for-each loop is normally written as a range-based for loop. Use auto or an explicit type for copied elements, auto& when the original elements must be modified, and const auto& for read-only access without unnecessary copies. The same loop form works with built-in arrays, strings, vectors, maps, and many other iterable C++ types.
In this C++ Tutorial, we learned how to use C++ foreach statement to execute a block of statements for each element in a collection or array of elements.
TutorialKart.com