link:
1.C++中的Range-based的循环
for ( range_declaration : range_expression )
loop_statement
如上面代码所示,这个for中有两个参数,一个是参数声明,另一个是循环的主体。可以注意的是,它甚至没有大括号。
以下是一些实例:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main(){
//使用vector循环
vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
cout << i << ' ';
//使用数组循环
int a[] = {0, 1, 2, 3, 4, 5};
for(int n : a)
cout << n << ' ';
//使用没声明的数组循环
for(int n : {0, 1, 2, 3, 4, 5})
cout << n << ' ';
//使用字符串循环
string str="Geeks";
for(char c : str)
cout << n << ' ';
//使用MAP类型类循环
map <int, int> MAP({{1, 1}, {2, 2}, {3, 3}});
for (auto i : MAP)
std::cout << '{' << i.first << ", "
<< i.second << "}\n";
}
2.C++中的for_each循环
for_each (InputIterator start_iter, InputIterator last_iter, Function fnc)
从模板中看出,第一个参数是 起始位置,第二个是 最后位置, 第三个是 执行的函数。有以下例子:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void printx2(int a){
cout << a * 2 << " ";
}
struct Class2{
void operator() (int a){
cout << a * 3 << " ";
}
} ob1;
int main(){
int arr[5] = { 1, 5, 2, 4, 3 };
cout << "Using Arrays:" << endl;
//这是输出初始的数组
for_each(arr, arr + 5, printx2);
//执行的主体已经在for_each的循环中了。
//可见,我们会让它执行5次。
for_each(arr, arr + 5, ob1);
//直接调用对象,对数组中的5个元素进行执行
vector<int> arr1 = { 4, 5, 8, 3, 1 };
//执行数组的向量
for_each(arr1.begin(), arr1.end(), printx2);
//从vector中取数循环
for_each(arr1.begin(), arr1.end(), ob1);
//使用对象的方法,循环
}