`
xitongyunwei
  • 浏览: 934979 次
文章分类
社区版块
存档分类
最新评论

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 twentiesI 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;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics