Range-based for loop in C++
The range-based for loop in C++ is a convenient feature that simplifies iterating over elements in a container or any other type that implements an iterator.
Syntax
for (auto element : container) {
// code
}
Here, "element" is a variable that will be assigned each value in the container. The "auto" keyword tells the compiler to determine the appropriate type of element based on the type of container.
Example
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {1, 2, 3, 4, 5};
for (auto num : nums) {
cout << num << " ";
}
return 0;
}
Output
1 2 3 4 5
Explanation
In the above example, we have used the range-based for loop to iterate over each element in the "nums" vector. The loop assigns each element to the "num" variable and executes the code block inside the loop.
Use
The range-based for loop is useful when you need to iterate over the elements of a container or any other type that supports iteration, such as an array. It simplifies the syntax and makes the code more readable.
#include <iostream>
#include <string>
using namespace std;
int main() {
string word = "hello";
for (auto letter : word) {
cout << letter << " ";
}
return 0;
}
In the above example, we have used the range-based for loop to iterate over each character in the "word" string.
Important Points
- The range-based for loop simplifies iteration over elements in a container or any other type that supports iteration.
- The loop automatically assigns each element to a variable.
- The "auto" keyword is used to determine the appropriate type of the variable.
- The loop can be used with any type that implements an iterator.
Summary
In summary, the range-based for loop in C++ is a convenient feature that simplifies iteration over elements in a container or any other type that supports iteration. It makes the code more readable and avoids the need for cumbersome iterators or counter variables.