CS/C, C++
[C++] std::accumulate
겸둥이xz
2021. 2. 8. 18:30
반응형
std::accumualte
#include <iostream>
#include <numeric>
using namespace std;
int main() {
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = accumulate(array, array + 10, 0);
cout << "sum : " << sum << "\n"; // sum : 55
int product = accumulate(array, array + 10, 1, multiplies<int>());
cout << "product : " << product << "\n"; // product : 3628800
long long arrayL[10] = {2e9, 3e9};
long long longSum = accumulate(arrayL, arrayL + 2, 0LL); // longSum : 5000000000
cout << "longSum : " << longSum << "\n";
return 0;
}
<numeric> 헤더에 포함된 함수이고, 보통 배열 또는 벡터 원소들의 합을 구할 때 사용
accumulate의 첫 번째, 두 번째 인자는 각각 first, last iterator가 들어가고, 세 번째 인자는 initial value이다.
int sum을 구하는 경우에는 합의 초기값 0이 들어가고, 곱의 경우에는 1을 넣는다.
주의점!! accumlate의 반환값이 initial value의 타입을 따라간다.
int sum = accumulate(array, array + 10, 0);
int의 경우에는 initail value를 0으로 하지만
long long longSum = accumulate(arrayL, arrayL + 2, 0LL);
long long의 경우에는 0LL로 주어야 한다.
반응형