|
궁금이 님이 쓰신 글 :
: 꼭 좀 부탁드릴께요
:
: 설명도 함께 해주심 더 감사하구요^^
그에 대한 벌(?)로 1번 문제를 제 맘대로 풀어드리죠.
아래의 코드를 해석하는 고통을 받으세요.^^;
반복문(for, do-while, while)을 전혀 사용하지 않고,
등차수열을 구하는 함수(function) 대신 함수 객체(function object)를 대신 사용하는 소스입니다.
시대에 뒤떨어진 반복문을 사용하는 시대는 이미 지났습니다. ^^;
//---------------------------------------------------------------------------
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iterator>
//---------------------------------------------------------------------------
using namespace std;
// 등차수열의 일반항을 구하는 사용자 정의 함수 객체(user-defined function object)
class arith_series: public unary_function<double, double>
{
public:
arith_series(double first_term, double diff, double term):
a0(first_term), d(diff), n(term) {}
double operator()(double term) { return a0 + d * n++; }
private:
double a0, d, n;
};
int main()
{
const double a0 = 1.0, d = 3.0;
const int num_terms = 10;
vector<double> v_arith_series(num_terms);
generate(v_arith_series.begin(), v_arith_series.end(), arith_series(a0, d, 0));
// arith_series 함수 객체의 호출은 함수 호출과 동일한 형태임에 유의하세요.
copy(v_arith_series.begin(), v_arith_series.end(),
ostream_iterator<double>(cout, " "));
double sum = accumulate(v_arith_series.begin(), v_arith_series.end(), 0),
average = sum / num_terms;
cout << "\nSum = " << sum << ", Average = " << average << endl;
return 0;
}
//---------------------------------------------------------------------------
결과는 물론 다음과 같습니다.
1 4 7 10 13 16 19 22 25 28
Sum = 145, Average = 14.5
|