RangeBased for Loop in C++ (original) (raw)
Range-Based for Loop in C++
Last Updated : 21 May, 2025
In C++, the **range-based for loop introduced in C++ 11 is a version of for loop that is able to iterate over a range. This range can be anything that is iteratable, such as arrays, strings and STL containers. It provides a more readable and concise syntax compared to traditional for loops.
Let's take a look at an example:
C++ `
#include <bits/stdc++.h> using namespace std;
int main() { vector v = {1, 2, 3, 4, 5};
// Iterating through vector
for (int i : v) {
cout << i << " ";
}
return 0;
}
`
**Explanation: In this program, the vector is iterated using range based for loop. As we can see, we don't need to pass any size information or any iterator to iterate the vector. We just use the name of the vector.
Syntax of Range Based for Loop
C++ `
for (declaration: range) { // statements }
`
where,
- **declaration: Declaration of the variable that will be used to represent each element of the range.
- **range: Name of the range.
The range-based for loop simplifies iteration over containers in C++.
Examples of Range Based for Loop
The below example demonstrates the use of range based for loop in our C++ programs:
Iterate over an Array using Range Based for Loop
C++ `
#include using namespace std;
int main() { int arr[] = {1, 2, 3, 4, 5};
// Range based for loop to iterate over array
// and i is used to represent each element
for (int i : arr) {
cout << i << " ";
}
return 0;
}
`
Iterate over a Map using Range Based for Loop
Each element of the map is a pair of the same type as that of a map. We have to specify that in declaration, or we can use **auto keyword.
C++ `
#include <bits/stdc++.h> using namespace std;
int main() { map<int, char> m = {{1, 'A'}, {2, 'B'}, {3, 'C'}, {4, 'D'}, {5, 'E'}};
// Range based for loop to iterate over array
// and i is used to represent each element
for (auto p: m) {
cout << p.first << ": " << p.second << endl;
}
return 0;
}
`
Output
1: A 2: B 3: C 4: D 5: E
Since C++ 17, there is also another method of declaration of range based for loop.
C++ 17 `
#include <bits/stdc++.h> using namespace std;
int main() { map<int, char> m = {{1, 'A'}, {2, 'B'}, {3, 'C'}, {4, 'D'}, {5, 'E'}};
// Range based for loop to iterate over array
// and i is used to represent each element
for (auto [k, v]: m) {
cout << k << ": " << v << endl;
}
return 0;
}
`
**Output
1: A
2: B
3: C
4: D
5: E
Iterate Vector by Reference using Range Based for Loop
By default, the variable that represents each element is a copy of the element. We cannot make changes in actual range using that variable. In this case, we have to declare it as a reference as shown in the below program.
C++ `
#include <bits/stdc++.h> using namespace std;
int main() { vector v = {1, 2, 3, 4, 5};
// Increment each element
for (auto i: v) {
i++;
}
// Increment each element using reference
for (auto& i: v) {
i++;
}
// Iterating through vector
for (auto& i : v)
cout << i << " ";
return 0;
}
`