[C++] accumulate 함수

yeseo·2024년 12월 10일

C++

목록 보기
3/3

accumulate

numeric 라이브러리에 속해있는 배열의 합을 반환하는 함수이다.

accumulate(first, last, init, binary_op)

  1. first, last: first부터 last까지의 연산할 원소들을 결정한다.
  2. init: 초기값으로, init에서부터 원소들을 더한다. init의 자료형에 따라 함수 반환값의 자료형이 결정되므로 주의해야 한다.
  3. binary_op: 원하는 누적 계산을 지정한다. 생략이 가능하며 이 함수는 기본적으로 +연산을 수행한다.

    std::multiplies()와 같이 이미 정의되어있는 함수나 사용자가 제작한 함수도 가능하다.


예시

배열의 평균값을 구하는 함수를 작성해보자. 아래는 accumulate 함수 없이 작성한 코드이다.

#include <string>
#include <vector>

using namespace std;

double solution(vector<int> numbers) {
    
    double solution = 0.f;
    // 배열 값 더하기
    for (int i : numbers) {
        solution += i;
    }
    
    // 평균 내기
    solution /= numbers.size();
    
    // 리턴
    return solution;
}

accumulate 함수를 적용한 코드는 아래와 같다. 위 코드보다 간결해 진 것을 볼 수 있다.
#include <string>
#include <vector>
#include <numeric>

using namespace std;

double solution(vector<int> numbers) {
    
    return accumulate(numbers.begin(),numbers.end(),0.0) / numbers.size();
}


참고
https://en.cppreference.com/w/cpp/algorithm/accumulate
https://learn.microsoft.com/ko-kr/cpp/standard-library/numeric-functions?view=msvc-170

0개의 댓글