Calculate 1 plus to 100 by Using C++

When Gauss was ten,he calculated 1+2+3+4+…..+99+100 like this:(1+100)*100/2 =5050

Now in my twenties I calculated it by Using C++ as below:

#include "iostream"
#include "string.h"
#include <vector>
#include <algorithm>

using namespace std;

template<class T> class n_Sum;

template<class T> class n_Sum_Implt
{
 T sum;
 friend class n_Sum <T>;
 
public:
 
 n_Sum_Implt(T i=0):sum(i)
 {
 }
 
 void operator()(const T& value)
 {
  sum += value;
 }
};

 

template<class T> class n_Sum
{
 T sum;
 n_Sum_Implt<T>* pn_Sum_Implt;
public:
 
 n_Sum(T i=0):sum(i)
 {
 }
 
 void SetImplentPtr(n_Sum_Implt<T>* pImplt)
 {
  pn_Sum_Implt = pImplt;
 }
 
 void operator()(const T& x)
 {
  pn_Sum_Implt->operator() (x);
 }
 
 T result() const
 {
  return pn_Sum_Implt->sum;
 }
};

 

int main()

 
 int i;
 vector<int> vi;
 
 n_Sum<int> sum;
 n_Sum_Implt<int> sumImplt;
 
 sum.SetImplentPtr(&sumImplt);
 
 for(i=1; i<=100; i++)
 {
  vi.push_back(i);
 }
 
 for_each(vi.begin(), vi.end(), sum);
 cout<<"result:"<<sum.result()<<endl;
 return 0;
}

你可能感兴趣的:(Calculate 1 plus to 100 by Using C++)