How to calculate vector mean value using for_each() in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <algorithm>

using std::vector;
using std::cout;
using std::endl;

class Mean {
private:
	long total_elements;   
	long sum_elements;    
public:
	Mean() : total_elements(0), sum_elements(0) {}

	void operator() (int element) {
		total_elements++;         
		sum_elements += element;  
	}
	double value() {
		return static_cast<double>(sum_elements) / static_cast<double>(total_elements);
	}
};


int main()
{
	vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

	Mean m = for_each(vec.begin(), vec.end(), Mean());

	cout << m.value() << endl;
}

/*
run:

5.5

*/

 



answered Jan 25, 2018 by avibootz

Related questions

...