Range-based for loop in C++
Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.
Syntax :
for ( range_declaration : range_expression )
loop_statement
Parameters :
range_declaration :
a declaration of a named variable, whose type is the
type of the element of the sequence represented by
range_expression, or a reference to that type.
Often uses the auto specifier for automatic type
deduction.
range_expression :
any expression that represents a suitable sequence
or a braced-init-list.
loop_statement :
any statement, typically a compound statement, which
is the body of the loop.
C++ implementation :
// Illustration of range-for loop // using CPP code #include <iostream> #include <vector> #include <map> //Driver int main() { // Iterating over whole array std::vector<int> v = {0, 1, 2, 3, 4, 5}; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; // the initializer may be a braced-init-list for (int n : {0, 1, 2, 3, 4, 5}) std::cout << n << ' '; std::cout << '\n'; // Iterating over array int a[] = {0, 1, 2, 3, 4, 5}; for (int n : a) std::cout << n << ' '; std::cout << '\n'; // Just running a loop for every array // element for (int n : a) std::cout << "In loop" << ' '; std::cout << '\n'; // Printing string characters std::string str = "Geeks"; for (char c : str) std::cout << c << ' '; std::cout << '\n'; // Printing keys and values of a map std::map <int, int> MAP({{1, 1}, {2, 2}, {3, 3}}); for (auto i : MAP) std::cout << '{' << i.first << ", " << i.second << "}\n"; } |
chevron_right
filter_none
Output:
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5
In loop In loop In loop In loop In loop In loop
G e e k s
{1, 1}
{2, 2}
{3, 3}
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- for_each loop in C++
- Print 1 to 100 in C++, without loop and recursion
- How will you print numbers from 1 to 100 without using loop?
- Difference between while and do-while loop in C, C++, Java
- Print pattern using only one loop | Set 1 (Using setw)
- What happens if loop till Maximum of Signed and Unsigned in C/C++?
- Print a character n times without using loop, recursion or goto in C++
- Print a number 100 times without using loop, recursion and macro expansion in C?
- Structures in C++
- Variables in C++
- Implementing Forward Iterator in BST
- Count substrings that contain all vowels | SET 2
- Machine Learning in C++
- How can we use Comma operator in place of curly braces?
Improved By : ChrisFedun




