// These are my template function to work with containers. Always pass iterators, never containers directly ! // // courtesy of orsone.mi.inf.it using namespace std; namespace mySTD { template void print(_ForwardIterator __first, _ForwardIterator __last) { unsigned int i = 0; for (_ForwardIterator __i = ++__first; __i != __last; ++__i) { cout << "Element " << i << " = " << (*__i) << endl; i++; } } template double myVar(_ForwardIterator __first, _ForwardIterator __last) { double result=0.; if (__first == __last) return result; double old_average, average=0.; double sumx = 0; double sumx2 = 0; for (_ForwardIterator __i = __first; __i != __last; ++__i) { sumx += static_cast(*__i); sumx2 += static_cast(*__i)*static_cast(*__i); } result = 1./static_cast(__last-__first) * ( sumx2 - (sumx*sumx/static_cast(__last-__first))) ; return result; } template double myAve(_ForwardIterator __first, _ForwardIterator __last) { double result=0.; if (__first == __last) return result; for (_ForwardIterator __i = __first; __i != __last; ++__i) { result += static_cast(*__i); } result = result/static_cast(__last-__first) ; return result ; } // this is an improved version of the average calculation. Avoid large sums template double myAve_improved(_ForwardIterator __first, _ForwardIterator __last) { double result=0.; if (__first == __last) return result; double average=0.; unsigned int i =0 ; for (_ForwardIterator __i = __first; __i != __last; ++__i) { average = static_cast(i)/static_cast(i+1)*average + 1./static_cast(i+1)*static_cast(*__i); i++; } return average; } // this is an improved version of the Variance calculation. Avoid large sums template double myVar_improved(_ForwardIterator __first, _ForwardIterator __last) { double result=0.; if (__first == __last) return result; double old_average, average=0.; unsigned int i =0 ; for (_ForwardIterator __i = __first; __i != __last; ++__i) { old_average = average; average = static_cast(i)/static_cast(i+1)*average + 1./static_cast(i+1)*static_cast(*__i); result = 1./static_cast(i+1) * (static_cast(i) * result + static_cast(*__i)*static_cast(*__i) + static_cast(i) * old_average*old_average - static_cast(i+1) * average*average ); i++; } return result; } template void ReadVector( string filename , unsigned int n , T & data) { double temp; ifstream inputFile(filename); if ( !inputFile ) { cout << "Cannot open file " << filename << endl; } else { for (unsigned int i=0; i> temp; data.push_back( static_cast (temp) ); if ( inputFile.eof() ) { cout << "Stop reading after " << i << " entries!" << endl; break; } } } } }