In my previous articles about C++11 standard I talked about automatic type detection , decltype keyword and uniform initializer list introduced in C++11. Lets see the Range-based for loop today:
Earlier, the for loop which we use to traverse a list has unnecessary counter increment and check for the last element in the list. For example:If I want to print all the elements in an array, then the code will be
// C++03 code int arr[10] = {0,1,2,3,4,5,6,7,8,9}; for(int cnt=0; cnt < 10; cnt++) cout << arr[cnt] << endl;
Languages like java and C# already had for each loop which is easier to use in such cases. the java code will be
// Java Code for(int x : arr) System.out.println(x); // similar to cout in C++
C++11 introduces range-based for loop which is similar to for-each loop of other languages. The above code in C++11 will be
// C++11 Code int arr[10] = {0,1,2,3,4,5,6,7,8,9}; for (int &x : arr) cout << x << endl;
Lets look at a more complex problem:
// Code before C++11 map another_class_map; for (map<myclass, vector>::const_iterator it = another_class_map.begin(); it != another_class_map.end(); ++it) { .... } // C++11 Code map<myclass, vector> another_class_map; for (auto x : another_class_map) { .... }
See how convenient
Previous: Uniform Initializer List in C++11
Next: Separate Null Pointer in C++11
2 Comments
[…] articles on C++, I have written about the automatic type detection, uniform initialization list and Range based for loopin C++11. Earlier we used to use the NULL macro which is synonymous to int 0. This came as an inheritance […]
[…] Automatic type detection and decltype Next: Range based for loop similar to for-each Posted by krawat Tagged with: C++11, initializer […]