언어/C++
accumulate의 사용법과 활용
alpacadabra
2023. 5. 15. 17:36
accumulate는 컨테이너 내부의 원소들에 대하여 누적 값을 구할 때 사용된다.
값은 무엇이든 될 수 있다. 기본적으론 합을 구하지만 아래와 같이 곱도 구할 수 있다.
std::vector<int> v = { 1,2,3,4,5 };
std::cout << "누적 합: " << std::accumulate(v.begin(), v.end(), 0 /*,std::plus<int>()*/) << std::endl;
std::cout << "누적 곱: " << std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>()) << std::endl;
accumulate의 3번째 매개 변수는 초기값이고 4번째는 이항 연산이다.
위 코드에서는 빌트인 연산을 인자로 전달하였는데, 아래와 같이 커스텀 연산을 전달할 수도 있다.
#include <iostream>
#include <vector>
#include <string>
#include <numeric>
using namespace std;
int main()
{
vector<string> v = { "1", "22", "333", "4444", "55555" };
cout << "길이의 누적 합: " <<
accumulate(v.begin(), v.end(), 0, [](int res, string s) {return res + s.length(); }) << endl;
cout << "길이의 누적 곱: " <<
accumulate(v.begin(), v.end(), 1, [](int res, string s) {return res * s.length(); }) << endl;
}
이렇듯 accumulate를 활용하면 반복문을 작성할 필요가 없으므로 코드가 비교적 깔끔해진다는 장점이 있다.
시험삼아 작성해보고 싶다면 아래의 간단한 문제를 풀어봐도 좋다.
코딩테스트 연습 - 길이에 따른 연산 | 프로그래머스 스쿨 (programmers.co.kr)