Q) 1, 1+2, 1+2+3, ... , 1+2+3+4+......+19+20 의 각 항을 구하시오.
A)
STL을 써서, for 루프를 쓰지 않고 구현하는 방법입니다.
iota 알고리듬:
1씩 증가하는 등차수열을 만드는 알고리듬입니다.
이 알고리듬은 ANSI C++ 표준에는 없고, STLport에 있습니다.
빌더 6에는 기본으로 설치되어 있지만, 빌더 5이하에서는 따로 설치하시거나,
다음과 같이 간단하게 구현하시면 됩니다.
template <class ForwardIterator, class T>
void iota(ForwardIterator first, ForwardIterator last, T value)
{
while (first != last)
*first++ = value++; // 엄청 간단하죠? ^^;
}
partial_sum 알고리듬:
위의 문제의 경우와 같은, 수열의 부분합(partial sum)을 구하는 알고리듬입니다.
template <class InputIterator, class OutputIterator>
OutputIterator partial_sum(InputIterator first, InputIterator last,
OutputIterator result);
예제는 다음과 같습니다.
// Illustrating the generic partial_sum algorithm
#include <iostream>
#pragma hdrstop
#include <algorithm>
#include <numeric>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
cout << "Illustrating the generic iota and partial_sum algorithm.\n";
const int N = 20;
vector<int> x1(N), x2(N);
iota(x1.begin(), x1.end(), 1);
ostream_iterator<int> out(cout, " ");
copy(x1.begin(), x1.end(), out);
cout << endl;
// Compute the partial sums of 1, 2, 3, ..., N
// putting the result in x2:
partial_sum(x1.begin(), x1.end(), x2.begin());
copy(x2.begin(), x2.end(), out);
cout << endl;
return 0;
}
|