for_each算法用於遍歷容器中的元素,前提是容器必須要提供迭代器,例如stack容器、queue容器本身不提供迭代器,所以不能使用for_each算法。
for_each的源碼(P.J. Plauger版本)實現如下:
template<class _InIt,class _Fn1>inline
void for_each(_InIt _First, _InIt _Last,_Fn1 _Func)
{
for(; _First != _Last; ++_First)
_Func(*_First);
}
可看到for_each算法有三個參數,容器開始迭代器,容器結束迭代器,加上一個回調(這裏可寫函數對象,或者普通函數)。
1. for_each基本用法
//普通函數
void print01(int val){
cout<< val << " ";
}
//函數對象
struct print001{
void operator()(int val){
cout<< val << " ";
}
};
//for_each算法基本用法
void test01(){
vector<int> v;
for (int i = 0; i < 10;i++){
v.push_back(i);
}
//遍歷算法
for_each(v.begin(), v.end(), print01);
cout<< endl;
for_each(v.begin(), v.end(), print001());
cout<< endl;
}
2. for_each返回值
struct print02{
print02(){
mCount= 0;
}
void operator()(int val){
cout<< val << " ";
mCount++;
}
int mCount;
};
//for_each返回值
void test02(){
vector<int> v;
for (int i = 0; i < 10; i++){
v.push_back(i);
}
print02 p = for_each(v.begin(), v.end(), print02());
cout<< endl;
cout<< p.mCount << endl;
}
struct print03 : public binary_function<int, int, void>{
void operator()(int val,int bindParam) const{
cout<< val + bindParam << " ";
}
};
3. 綁定參數輸出
//for_each綁定參數輸出
void test03(){
vector<int> v;
for (int i = 0; i < 10; i++){
v.push_back(i);
}
for_each(v.begin(), v.end(), bind2nd(print03(),100));
}