numeric 라이브러리에 속해있는 배열의 합을 반환하는 함수이다.
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;
}
#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