STL中支持迭代器的容器可以用for_each来做循环迭代
以下是一个demo:
#include <iostream>
#include <algorithm>
using namespace std;
#include <string>
void add10(int& element)
{
element += 10;
}
string print(int element)
{
cout << element << ' ';
return "芙蓉";
}
class add{
int delta;
public:
add(int d):delta(d){}
/*通过重载()使得类具有函数的类似函数的特性*/
void operator()(int& element){
element += delta;
}
};
/*模拟for_each*/
template <typename Iter, typename Func>
void foreach(Iter ib, Iter ie, Func f)
{
while(ib!=ie) f(*ib++);
}
int main()
{
int a[5] = {11,22,33,44,55};
for_each(a,a+5,add10);
for_each(a,a+5,print);cout<<endl;
for_each(a,a+5,add(5));
for_each(a,a+5,print);cout<<endl;
for_each(a,a+5,add(1));
for_each(a,a+5,print);cout<<endl;
}
/*输出:
21 32 43 54 65
26 37 48 59 70
27 38 49 60 71
*/