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强制类型转换:

    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;
 

/*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强制类型转换:

	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;

*/

#include 
#include 
#include 
using namespace std;

void print(int elem)
{
	cout << elem << ' ';
}
template
class AddValue
{
private:
	T theValue;
public:
	AddValue(const T& v) :theValue(v) {}
	void operator()(T& elem) const
	{
		elem += theValue;
	}
};
class MeanValue
{
private:
	long num;
	long sum;
public:
	MeanValue() :num(0), sum(0) {}
	void operator()(int elem)//operator就是函数对象
	{
		num++;
		sum += elem;
	}
	double value()
	{
		return static_cast(sum) / static_cast(num);
		//static_cast强制类型转换:
		 //https://blog.csdn.net/txwtech/article/details/104148011
	}

	//类型转换函数operator double(),double运算符重载
	//参考:https://www.cnblogs.com/txwtech/p/12115391.html
	operator double()
	{
		return static_cast(sum) / static_cast(num);
	}

};

int main()
{
	vector ivec;
	for (int i = 1; i <= 9; ++i)
		ivec.push_back(i);
	for_each(ivec.begin(), ivec.end(), print);
	cout << endl;
	for_each(ivec.begin(), ivec.end(), AddValue(10));//函数对象,自动调用operator
	for_each(ivec.begin(), ivec.end(), print);
	cout << endl;
	for_each(ivec.begin(), ivec.end(), AddValue( *ivec.begin()));
	for_each(ivec.begin(), ivec.end(), print);
	cout << endl;
	 // MeanValue()是函数对象,返回也是函数对象
	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;


	return 0;
}

 

你可能感兴趣的:(C++)