C++ Range-Based For Loop (C++11)
The range-based for loop in C++11 allows iterating over all elements of a container, array, or collection without explicitly managing indices or iterators.
1. Basic Range-Based For Loop Example
This example iterates through an array of integers using the range-based for loop.
C++
Example: Basic range-based for loop
#include <iostream>
using namespace std;
int main() {
int numbers[] = {1, 2, 3, 4, 5};
for (int num : numbers) {
cout << num << endl;
}
return 0;
}
2. Using With Containers
Range-based for loops work with standard containers like vector, list, or array.
C++
Example: Range-based for loop with vector
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {10, 20, 30};
for (int x : v) {
cout << x << endl;
}
return 0;
}
3. Common Mistakes
A common mistake is modifying elements without using references. Use & to modify container elements safely.
C++
Correct modification example
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {1, 2, 3};
for (int &x : v) { // Use reference to modify
x *= 2;
}
for (int x : v) {
cout << x << endl;
}
return 0;
}
Conclusion
C++ range-based for loops simplify iteration over arrays and containers, making code cleaner and reducing errors. Use references when you need to modify elements.
Codecrown