Range-based for loop:
For built-in arrays and classes (such as std::string) and STL containers that contain method begin () and end (), scope-based for loops can simplify the work of writing loops for them. This loop performs the specified action on each element in the array or container:
#include <iostream>int main(){ double prices[5] = {4.99,10.99,6.87,7.99,8.49}; for (double x : prices) std::coutstd::endl; return0;}
where x will sequentially be the value of each element in prices. The type of x should match the type of the array element. An easier and more secure way is to use Auto to declare x, so the compiler infers the type of x based on the information declared by prices:
for (auto x : prices) std::coutstd::endl;
If you want to modify each element of an array or container in a loop, you can use a reference type:
std::vector<int> vi(6);for (auto &x : vi) std::rand();
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + + 11 range-based for loop