Range-based For Loop in C++
Introduction
The range-based for loop is a feature introduced in C++11 that allows for simpler and more readable iterations over containers and arrays. It is an enhancement over the traditional for loop, providing a more concise syntax for looping through elements in a range.
Syntax
The syntax for a range-based for loop is as follows:
for (declaration : range) {
// loop body
}
Here, declaration
is a variable that will represent each element in the range, and range
is the container or array being iterated over.
Example 1: Iterating Over an Array
The following example demonstrates how to use a range-based for loop to iterate over an array of integers:
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4, 5};
for (int num : arr) {
std::cout << num << " ";
}
return 0;
}
This code will output:
Example 2: Iterating Over a Vector
The range-based for loop can also be used with other containers such as vectors. Here is an example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {10, 20, 30, 40};
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
This code will output:
Modifying Elements
If you need to modify the elements of the range, you can use a reference in the declaration. Here is an example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {10, 20, 30, 40};
for (int &num : vec) {
num += 5;
}
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
This code will output:
Auto Keyword
The auto
keyword can be used in the declaration to let the compiler deduce the type of the elements in the range. Here is an example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
for (auto num : vec) {
std::cout << num << " ";
}
return 0;
}
This code will output:
Conclusion
The range-based for loop is a powerful and convenient feature in C++ that simplifies the process of iterating over containers and arrays. By using this loop, you can write cleaner and more readable code.