STL源码
template<typename InputIterator, typename Function>
Function for_each(InputIterator beg, InputIterator end, Function f) {
while(beg != end)
f(*beg++);
}
例子,这样写可以避免显示的调用迭代器变量
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Play
{
void operator () (int i)
{
cout << i << endl;
}
};
int main()
{
vector<int> ilist = { 1,2,3,4,5,6,7 };
for_each(ilist.begin(), ilist.end(), Play());
std::cout << "Hello World!\n";
}
void print(int i)
{
cout<<i<<" ";
}
class Int
{
public:
explicit Int(int i):m_i(i)
{
}
~Int()
{
}
void print1()
{
cout<<"["<<m_i<<"] ";
}
private:
int m_i;
};
int ia2[] = {2,21,12,7,19,23};
vector<int> iv(ia2,ia2+6);
cout<<count_if(iv.begin(),iv.end(),not1(bind2nd(less<int>(),12)));//4
cout<<endl;
for_each(iv.begin(),iv.end(),print);//2 21 12 7 19 23
cout<<endl;
for_each(iv.begin(),iv.end(),ptr_fun(print));//2 21 12 7 19 23
cout<<endl;
Int t1(3),t2(7),t3(20),t4(14),t5(68);
vector<Int> Iv;
Iv.push_back(t1);
Iv.push_back(t2);
Iv.push_back(t3);
Iv.push_back(t4);
Iv.push_back(t5);
//当容器中存放的是对象实体的时候用mem_fun_ref
for_each(Iv.begin(),Iv.end(),mem_fun_ref(&Int::print1));//[3] [7] [20] [14] [68]
cout<<endl;
vector<Int*> Iv2;
Iv2.push_back(&t1);
Iv2.push_back(&t2);
Iv2.push_back(&t3);
Iv2.push_back(&t4);
Iv2.push_back(&t5);
//当容器中存放的是对象的指针的时候用mem_fun
for_each(Iv2.begin(),Iv2.end(),mem_fun(&Int::print1));//[3] [7] [20] [14] [68]
cout<<endl;