一 语法
attr(optional) for ( range_declaration : range_expression )
loop_statement (until C++20)
attr(optional) for ( init-statement(optional)range_declaration : range_expression )
loop_statement (since C++20)
二 举例
{
cout << "vc: ";
std::vector<int> vc {1,2,3};
for (auto i : vc) {
cout << i << " ";
}
cout << endl;
}
vc: 1 2 3
- 允许操作初值列和寻常的、大小已知的C-style array
{
cout << "sz: ";
int sz[] = {1, 2, 3};
for (auto i : sz) {
cout << i << " ";
}
cout << endl;
}
{
cout << "list: ";
for (auto i : {1, 2, 3}) {
cout << i << " ";
}
cout << endl;
}
sz: 1 2 3
list: 1 2 3
三 相关算法
bool even(int n){
if (n%2 ==0) {
cout << n << " is even " << endl;
return true;
}
return false;
}
{
std::vector<int> vc{1, 2, 3};
for_each(vc.begin(), vc.end(), even);
cout << endl;
}
2 is even
{
std::vector<int> vc{1, 2, 3};
for_each_n(vc.begin(), 2, even);
cout << endl;
}
2 is even
四 参考