In C++, the range-based for loop is a powerful construct that simplifies the process of iterating over elements in a container or a range. It provides an elegant and concise way to iterate through the elements without the need for manual indexing or iterators. In this article, we will explore the syntax and usage of the range-based for loop with examples.
Syntax of the Range-based For Loop
The syntax of the range-based for loop in C++ is as follows:
for (element_declaration : range_expression) { // code to be executed }
Here, the element_declaration
is a variable that will hold each element in the range, and the range_expression
is the range or container over which we want to iterate.
Example 1: Iterating over an Array
Let’s start with a simple example of iterating over an array using the range-based for loop:
#include <iostream> int main() { int numbers[] = {1, 2, 3, 4, 5}; for (int number : numbers) { std::cout << number << " "; } return 0; }
In this example, we have an array of integers named numbers
. The range-based for loop iterates over each element in the array and assigns it to the variable number
. We then print each number using std::cout
.
The output of this program will be:
1 2 3 4 5
Example 2: Iterating over a Vector
The range-based for loop can also be used to iterate over other containers like vectors. Let’s see an example:
#include <iostream> #include <vector> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; for (int number : numbers) { std::cout << number << " "; } return 0; }
In this example, we have a vector of integers named numbers
. The range-based for loop iterates over each element in the vector and assigns it to the variable number
. We then print each number using std::cout
.
The output of this program will be the same as the previous example:
1 2 3 4 5
Example 3: Iterating over a String
The range-based for loop can also be used to iterate over strings. Let’s see an example:
#include <iostream> #include <string> int main() { std::string message = "Hello, World!"; for (char c : message) { std::cout << c << " "; } return 0; }
In this example, we have a string named message
. The range-based for loop iterates over each character in the string and assigns it to the variable c
. We then print each character using std::cout
.
The output of this program will be:
H e l l o , W o r l d !
Conclusion
The range-based for loop in C++ provides a concise and readable way to iterate over elements in a range or container. It simplifies the process of iteration by eliminating the need for manual indexing or iterators. It can be used with arrays, vectors, strings, and other containers, making it a versatile tool for iterating over various data structures.
By utilizing the range-based for loop, you can write cleaner and more expressive code, enhancing the readability and maintainability of your C++ programs.