algorithm_reduce

algorithm_reduce (누적 축약)

std::reduce는 범위를 병렬 친화적으로 축약(reduce)해서 누적 합계를 구해요. std::accumulate와 달리 요소 순서가 보장되지 않아 병렬화에 유리하지만, 순서가 중요하면 안 돼요.

출처: cppreference

본문

std::reduce<numeric> 헤더에 정의되어 있어요. C++17부터 사용 가능해요.

template< class InputIt >
typename std::iterator_traits<InputIt>::value_type
    reduce( InputIt first, InputIt last );

template< class InputIt, class T >
T reduce( InputIt first, InputIt last, T init );

template< class InputIt, class T, class BinaryOp >
T reduce( InputIt first, InputIt last, T init, BinaryOp op );
  • 1번 오버로드reduce(first, last, typename std::iterator_traits<InputIt>::value_type{})와 동등해요.
  • 2번 오버로드reduce(first, last, init, std::plus<>())와 동등해요.
  • 3번 오버로드 — 범위 [first, last)를 초기값 init과 함께 이항 연산 op로 축약해요. 이때 요소들은 지정되지 않은 방식으로 순서가 바뀌고 결합될 수 있어요.

op가 비가환적이거나 비결합적이면 동작이 정의되지 않아요. 병렬 실행 정책을 받는 오버로드도 있어요.

반환값 (Return value)

축약의 결과예요.

참고 (Notes)

std::accumulate는 순차 순서를 보장하지만 std::reduce는 보장하지 않아요. 순서가 의미를 가지면 accumulate를 써야 해요.

예제 (Example)

#include <functional>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>

int main()
{
    std::vector<int> v{1, 2, 3, 4, 5};
    std::cout << std::reduce(v.begin(), v.end()) << '\n';
    std::cout << std::reduce(v.begin(), v.end(), 0, std::multiplies<int>{}) << '\n';
}

출력:

15
120

더 알아보기 (Learn more)

cppreference