cb35a_c++_STL_算法_for_each
cb35a_c++_STL_算法_for_each
for_each(b,e,p)
使用for_each()算法遍历数据
使用for_each()和函数对象修改数据
使用for_each()的返回值
//转换函数operator double()
//参考:https://www.cnblogs.com/txwtech/p/12115391.html
//static_cast<double>强制类型转换:
MeanValue mv=for_each(ivec.begin(), ivec.end(), MeanValue());//for_each的返回值给到mv,mv里面保留了 num与sum的结果。
cout << "平均值:" << mv.value() << endl;
double result= for_each(ivec.begin(), ivec.end(), MeanValue());
//for_each的返回值给到result,result定义为了doubule,它自动调用类型转换函数operator double()
cout << "平均值2:" << result << endl;
1 /*cb35a_c++_STL_算法_for_each 2 3 for_each(b,e,p) 4 使用for_each()算法遍历数据 5 使用for_each()和函数对象修改数据 6 使用for_each()的返回值 7 8 //转换函数operator double() 9 //参考:https://www.cnblogs.com/txwtech/p/12115391.html 10 //static_cast<double>强制类型转换: 11 12 MeanValue mv=for_each(ivec.begin(), ivec.end(), MeanValue());//for_each的返回值给到mv,mv里面保留了 num与sum的结果。 13 cout << "平均值:" << mv.value() << endl; 14 15 double result= for_each(ivec.begin(), ivec.end(), MeanValue()); 16 //for_each的返回值给到result,result定义为了doubule,它自动调用类型转换函数operator double() 17 cout << "平均值2:" << result << endl; 18 19 */ 20 21 #include <iostream> 22 #include <algorithm> 23 #include <vector> 24 using namespace std; 25 26 void print(int elem) 27 { 28 cout << elem << ' '; 29 } 30 template<class T> 31 class AddValue 32 { 33 private: 34 T theValue; 35 public: 36 AddValue(const T& v) :theValue(v) {} 37 void operator()(T& elem) const 38 { 39 elem += theValue; 40 } 41 }; 42 class MeanValue 43 { 44 private: 45 long num; 46 long sum; 47 public: 48 MeanValue() :num(0), sum(0) {} 49 void operator()(int elem)//operator就是函数对象 50 { 51 num++; 52 sum += elem; 53 } 54 double value() 55 { 56 return static_cast<double>(sum) / static_cast<double>(num); 57 //static_cast<double>强制类型转换: 58 //https://blog.csdn.net/txwtech/article/details/104148011 59 } 60 61 //类型转换函数operator double(),double运算符重载 62 //参考:https://www.cnblogs.com/txwtech/p/12115391.html 63 operator double() 64 { 65 return static_cast<double>(sum) / static_cast<double>(num); 66 } 67 68 }; 69 70 int main() 71 { 72 vector<int> ivec; 73 for (int i = 1; i <= 9; ++i) 74 ivec.push_back(i); 75 for_each(ivec.begin(), ivec.end(), print); 76 cout << endl; 77 for_each(ivec.begin(), ivec.end(), AddValue<int>(10));//函数对象,自动调用operator 78 for_each(ivec.begin(), ivec.end(), print); 79 cout << endl; 80 for_each(ivec.begin(), ivec.end(), AddValue<int>( *ivec.begin())); 81 for_each(ivec.begin(), ivec.end(), print); 82 cout << endl; 83 // MeanValue()是函数对象,返回也是函数对象 84 MeanValue mv=for_each(ivec.begin(), ivec.end(), MeanValue());//for_each的返回值给到mv,mv里面保留了 num与sum的结果。 85 cout << "平均值:" << mv.value() << endl; 86 87 double result= for_each(ivec.begin(), ivec.end(), MeanValue()); 88 //for_each的返回值给到result,result定义为了doubule,它自动调用类型转换函数operator double() 89 cout << "平均值2:" << result << endl; 90 91 92 return 0; 93 }
欢迎讨论,相互学习。
cdtxw@foxmail.com