for_each是algorithm头文件包含的stl算法之一。
一、for_each的使用
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
template<typename T>
int pushNum(T &vec, int first, int last) {
int ret = 0;
if (first > last) {
ret = -1;
cout << "function pushNum first > last error" << ret << endl;
}
while (first <= last) {
vec.push_back(first);
first++;
}
return ret;
}
template<typename T>
void printNum(T &num) {
cout << num << " ";
}
int main(){
vector<int> vec;
pushNum(vec, 1, 10);
for_each(vec.begin(), vec.end(), printNum<int>);
cout << endl;
system("pause");
return 0;
}
输出结果:
二、for_each仿函数的用法
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
template<typename T>
int pushNum(T &vec, int first, int last) {
int ret = 0;
if (first > last) {
ret = -1;
cout << "function pushNum first > last error" << ret << endl;
}
while (first <= last) {
vec.push_back(first);
first++;
}
return ret;
}
template<typename T>
class Print {
private:
T num;
public:
Print(T t) :num(t) {}
void operator()(T& ele)const {
ele *= num;
}
};
int main(){
vector<int> vec;
pushNum(vec, 1, 10);
for_each(vec.begin(), vec.end(), Print<int>(2));
for_each(vec.begin(), vec.end(), printNum<int>);
cout << endl;
system("pause");
return 0;
}
输出结果:
三、for_each的返回值用法
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
template<typename T>
int pushNum(T &vec, int first, int last) {
int ret = 0;
if (first > last) {
ret = -1;
cout << "function pushNum first > last error" << ret << endl;
}
while (first <= last) {
vec.push_back(first);
first++;
}
return ret;
}
template<typename T>
class SUM {
private:
long sum_num;
public:
SUM() :sum_num(0) {}
void operator()(T ele) {
sum_num += ele;
}
operator double() {
return static_cast<double>(sum_num);
}
};
int main(){
vector<int> vec;
pushNum(vec, 1, 10);
double sum = for_each(vec.begin(), vec.end(), SUM<int>());
cout << sum << endl;
system("pause");
return 0;
}
输出结果:
这里注意一点,SUM类中必须有类型强制转换重载,具体强制转换的类型是什么视具体而定。