![]() |
VOOZH | about |
The range-based for loop, introduced in C++11, provides a simple and readable way to iterate over all elements of a range. It automatically traverses arrays, strings, and STL containers without requiring explicit indices or iterators.
1 2 3 4 5
Explanation: The range-based for loop automatically visits each element of the vector. There is no need to specify the container size or use iterators explicitly.
where,
The working of a range-based for loop is as follows:
The below example demonstrates the use of range based for loop in our C++ programs:
The following program prints all elements of an array using a range-based for loop.
1 2 3 4 5
Explanation: Each element of the array is accessed sequentially and assigned to the loop variable x.
Since each element of a map is stored as a key-value pair, the loop variable must represent a pair object. Using auto allows the compiler to determine the appropriate type automatically.
1: A 2: B 3: C 4: D 5: E
Since C++17, structured bindings can be used to directly access keys and values without referring to .first and .second.
Output
1: A
2: B
3: C
4: D
5: E
Explanation: Structured bindings unpack each key-value pair into separate variables, making the code more readable.
By default, the loop variable stores a copy of each element. To modify the original elements of the container, the loop variable must be declared as a reference.
2 3 4 5 6
Explanation: Since x is declared as a reference (auto&), modifications are applied directly to the elements stored in the vector.
The range-based for loop offers several benefits over traditional iteration methods, making code simpler, safer, and easier to read.