본문 바로가기
언어/C++

accumulate의 사용법과 활용

by alpacadabra 2023. 5. 15.
 

https://cplusplus.com/reference/numeric/accumulate/

function template <numeric> std::accumulate sum (1)template T accumulate (InputIterator first, InputIterator last, T init);custom (2)template T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op); Accumulate values in ra

cplusplus.com

 

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)

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

댓글