标签:
for_each(b,e,p)// 对容器中的数据进行遍历 b和e是一对儿迭代器 p是一个函数或者是函数对象
使用for_each()算法遍历数据
使用for_each()和函数对象修改数据
使用for_each()返回值
#include<iostream> #include<algorithm> #include<vector> using namespace std; void print(int elem) { cout << elem << ' '; } // 函数对象 template<class T> class AddValue { private: T theValue; public: AddValue(const T &v) : theValue(v){}; void operator()(T &elem)const { elem += theValue; } }; class MeanValue { public: long num; long sum; public: MeanValue() :num(0), sum(0){} // 定义operator 使其成为函数对象 void operator()(int elem) { num++; sum += elem; } double value() { return static_cast<double>(sum) / static_cast<double>(num); } operator double() // 类型转换运算符重载 { return static_cast<double>(sum) / static_cast<double>(num); } }; int main() { vector<int> ivec; for (int i = 1; i <= 9; i++) ivec.push_back(i); cout << endl; for_each(ivec.begin(), ivec.end(), print); cout << endl; MeanValue mv = for_each(ivec.begin(), ivec.end(), MeanValue()); cout << "平均值:" << mv.value() << endl; //for_each(ivec.begin(), ivec.end(), AddValue<int>(10)); for_each(ivec.begin(), ivec.end(), AddValue<int>(*ivec.begin())); for_each(ivec.begin(), ivec.end(), print); cout << endl; double result = for_each(ivec.begin(), ivec.end(), MeanValue()); cout << "平均值:" << result << endl; // system("pause"); return 0; }
标签:
原文地址:http://blog.csdn.net/taotaoah/article/details/52207958