[ create a new paste ] login | about

Link: http://codepad.org/H2ZC4RSO    [ raw code | output | fork ]

Bjarne - C++, pasted on Oct 21:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <numeric>
/**
* @brief 平均値
* @param[in] Iterator first	配列の先頭
* @param[in] Iterator last   配列の末尾
* @return sum / cou		平均値
*/
template<class ResultType>
typename std::iterator_traits<ResultType>::value_type average(ResultType first, ResultType last)
{
	typedef std::iterator_traits<ResultType>::value_type value_type;
	value_type cou = last - first;
	value_type sum = std::accumulate(first, last, value_type(0.0));
	return sum / cou;
}

template <typename ResultType>
class StandardDeviation
{
	/** @brief コンテナの要素値 */
	ResultType val_;
public:
	/**	@brief コンストラクタ */
	StandardDeviation( const ResultType& val ) : val_( val ){}
	/**
	* @brief 平方和を取得
	* @param[in] 要素 
	*/	
	void operator()( ResultType& elem ) const
	{
		elem -= val_;
		elem *= elem;
	}
};

using namespace std;

int main()
{
	vector<double> vec;

	vec.push_back(10.0);
	vec.push_back(20.0);
	vec.push_back(30.0);
	vec.push_back(40.0);
	vec.push_back(50.0);

	double AVE = 0.0;
	double D = 0.0;
	double SD = 0.0;

	AVE = average(vec.begin(), vec.end());
	cout << "平均は " << AVE << "\n";

	for_each( vec.begin(), vec.end(), StandardDeviation<double>( AVE ) );
	copy(vec.begin(), vec.end(), ostream_iterator<double>(cout, "\n"));

	D = std::accumulate(vec.begin(), vec.end(), 0.0) / vec.size();
	cout << "分散は  " << D << "\n";

	SD = sqrt(D);
	cout << SD  << "\n";

	

	return 0;
}


Output:
1
2
3
In function 'typename std::iterator_traits<_Iterator>::value_type average(ResultType, ResultType)':
Line 15: error: too few template-parameter-lists
compilation terminated due to -Wfatal-errors.


Create a new paste based on this one


Comments: