반응형

std::accumulate

//
template <class InputIterator, class T>   
T accumulate (InputIterator first, InputIterator last, T init);


template <class InputIterator, class T, class BinaryOperation>   
T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op);

 

  • <numeric>에 포함된 누적 함수.
  • first, last 범위의 모든 값을 누적하여 반환.
  • 기본 누적은 요소를 합하는 것,
  • 요소 합 이외의 다른 작업은 Binary_op로 지정할 수 있다.

 

Parameters

  • first, last : 사용되는 반복자의 범위
  • init : 누적 계산의 초기 값.
  • binary_op : 이진 연산 지정. (함수 포인터 or 함수 객체)

 

 

Example

1) 배열 예시

//
#include <iostream>     // std::cout
#include <functional>   // std::minus
#include <numeric>      // std::accumulate

int myfunction (int x, int y) {return x+2*y;}
struct myclass {
	int operator()(int x, int y) {return x+3*y;}
} myobject;

int main () {
  int init = 100;
  int numbers[] = {10,20,30};

  std::cout << "using default accumulate: ";
  std::cout << std::accumulate(numbers,numbers+3,init);
  std::cout << '\n';

  std::cout << "using functional's minus: ";
  std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>());
  std::cout << '\n';

  std::cout << "using custom function: ";
  std::cout << std::accumulate (numbers, numbers+3, init, myfunction);
  std::cout << '\n';

  std::cout << "using custom object: ";
  std::cout << std::accumulate (numbers, numbers+3, init, myobject);
  std::cout << '\n';

  return 0;
}

 

 

결과

using default accumulate: 160
using functional's minus: 40
using custom function: 220
using custom object: 280

 

 

2) std::vector의 요소들을 모두 합할 때 사용

//
#include <iostream>
#include <vector>
#include <numeric>

int main()
{
    std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 
    int sum = std::accumulate(v.begin(), v.end(), 0);
    
    std::cout << "sum: " << sum << std::endl;
}

 

결과

 

sum : 55 
반응형

'언어 | Framework > C++' 카테고리의 다른 글

[STL] Vector와 List의 차이  (0) 2021.03.16
woongs_93