The Range-Based for Loop (foreach) in C++
C++11 introduced the range-based for
loop, also known as the foreach
loop, which simplifies iterating over elements in a container like arrays or vectors.
Syntax of the Range-Based for
Loop
for (element_type element : container) {
// Code to execute
}
Example: Iterating Over an Array
#include <iostream>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
for (int num : numbers) {
std::cout << "Number: " << num << std::endl;
}
return 0;
}
Key Takeaways
- The range-based
for
loop simplifies iteration over containers. - Improves code readability and reduces the chance of errors.
- Requires C++11 or later.