You may experience the usage of foreach to iterate object/array/list using C#, PHP, etc. This feature is now now available in C++11. C++11 (f.k.a C++0x) is a new version of standard of C++ programming. If you are new to C++11, read my article on Compile C++11 in GCC
Following is the example how it can be done.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> #include <string> int main() { // integer array int num[] = { 1, 2, 3, }; // string array string name[] = { "John", "Emily", "Albert" }; // loop each item in num array for(auto n : num) std::cout << n << std::endl; // loop each item in name array for(auto s : name) std::cout << s << std::endl; return 0; } |
Output:
1
2
3
John
Emily
Albert
2
3
John
Emily
Albert
C++ Range-Based For Loop Example