Turbo-C
C++Builder  |  Delphi  |  FireMonkey  |  C/C++  |  Free Pascal  |  Firebird
볼랜드포럼 BorlandForum
 경고! 게시물 작성자의 사전 허락없는 메일주소 추출행위 절대 금지
터보-C 포럼
Q & A
FAQ
팁&트릭
강좌/문서
자료실
Lua 게시판
볼랜드포럼 홈
헤드라인 뉴스
IT 뉴스
공지사항
자유게시판
해피 브레이크
공동 프로젝트
구인/구직
회원 장터
건의사항
운영진 게시판
회원 메뉴
북마크
볼랜드포럼 광고 모집

C/C++ 팁&트릭
[5] [STL]iota와 partial_sum 알고리듬에 대하여
김백일 [cedar] 5939 읽음    2002-05-09 00:31
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;
}

+ -

관련 글 리스트
5 [STL]iota와 partial_sum 알고리듬에 대하여 김백일 5939 2002/05/09
Google
Copyright © 1999-2015, borlandforum.com. All right reserved.