Namespaces
Variants

std:: partial_sum

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
헤더 파일에 정의됨 <numeric>
template < class InputIt, class OutputIt >

OutputIt partial_sum ( InputIt first, InputIt last,

OutputIt d_first ) ;
(1) (constexpr since C++20)
template < class InputIt, class OutputIt, class BinaryOp >

OutputIt partial_sum ( InputIt first, InputIt last,

OutputIt d_first, BinaryOp op ) ;
(2) (constexpr since C++20)
1) 만약 [ first , last ) 가 비어 있으면, 아무 작업도 수행하지 않습니다.
그렇지 않으면, 다음 작업을 순서대로 수행합니다:
  1. InputIt value type 인 누산기 acc 를 생성하고 * first 로 초기화합니다.
  2. acc * d_first 에 할당합니다.
  3. 정수 i [ 1 , std:: distance ( first, last ) ) 범위 내에 있을 때, 다음 작업을 순서대로 수행합니다:
a) 계산 acc + * iter (C++20 이전) std :: move ( acc ) + * iter (C++20 이후) , 여기서 iter first 의 다음 i 번째 반복자입니다.
b) 결과를 acc 에 할당합니다.
c) acc [1] * dest 에 할당합니다. 여기서 dest d_first 의 다음 i 번째 반복자입니다.
2) (1) 와 동일하지만, 대신 op ( acc, * iter ) (C++20까지) op ( std :: move ( acc ) , * iter ) (C++20부터) 를 계산합니다.

주어진 binary_op 를 실제 이항 연산으로 사용:

  • 다음 조건 중 하나라도 만족되면 프로그램의 형식이 잘못되었습니다:
  • InputIt 의 값 타입이 * first 로부터 생성 가능하지 않습니다.
  • acc d_first 쓰기 가능 하지 않습니다.
  • binary_op ( acc, * iter ) (C++20 이전) binary_op ( std :: move ( acc ) , * iter ) (C++20 이후) 의 결과가 InputIt 의 값 타입으로 암시적으로 변환 가능하지 않습니다.
  • 주어진 d_last 반환될 반복자인 경우, 다음 조건 중 하나라도 만족되면 동작은 정의되지 않습니다:
  • binary_op [ first , last ) 또는 [ d_first , d_last ) 범위의 임의 요소를 수정합니다.
  • binary_op [ first , last ] 또는 [ d_first , d_last ] 범위 내의 모든 반복자나 부분 범위를 무효화합니다.


  1. 실제로 할당될 값은 이전 단계의 할당 결과입니다. 여기서는 할당 결과가 acc 라고 가정합니다.

목차

매개변수

first, last - 합산할 요소들의 범위 를 정의하는 반복자 쌍
d_first - 대상 범위의 시작점; first 와 동일할 수 있음
op - 적용될 이항 연산 함수 객체

함수의 시그니처는 다음에 해당해야 함:

Ret fun ( const Type1 & a, const Type2 & b ) ;

시그니처에 const & 가 필요하지 않음.
Type1 타입은 std:: iterator_traits < InputIt > :: value_type 타입의 객체가 Type1 로 암시적으로 변환 가능해야 함. Type2 타입은 InputIt 타입의 객체가 역참조된 후 Type2 로 암시적으로 변환 가능해야 함. Ret 타입은 InputIt 타입의 객체가 역참조되어 Ret 타입의 값을 할당받을 수 있어야 함. ​

타입 요구사항
-
InputIt LegacyInputIterator 요구사항을 충족해야 함.
-
OutputIt LegacyOutputIterator 요구사항을 충족해야 함.

반환값

마지막으로 기록된 요소의 다음 요소를 가리키는 반복자, 또는 d_first (만약 [ first , last ) 범위가 비어 있는 경우).

복잡도

주어진 N std:: distance ( first, last ) 인 경우:

1) 정확히 N-1 번의 operator + 적용.
2) 정확히 N-1 번의 이항 함수 op 적용.

가능한 구현

partial_sum (1)
template<class InputIt, class OutputIt>
constexpr // since C++20
OutputIt partial_sum(InputIt first, InputIt last, OutputIt d_first)
{
    if (first == last)
        return d_first;
    typename std::iterator_traits<InputIt>::value_type sum = *first;
    *d_first = sum;
    while (++first != last)
    {
        sum = std::move(sum) + *first; // std::move since C++20
        *++d_first = sum;
    }
    return ++d_first;
    // 또는 C++14부터:
    // return std::partial_sum(first, last, d_first, std::plus<>());
}
partial_sum (2)
template<class InputIt, class OutputIt, class BinaryOp>
constexpr // since C++20
OutputIt partial_sum(InputIt first, InputIt last, 
                     OutputIt d_first, BinaryOp op)
{
    if (first == last)
        return d_first;
    typename std::iterator_traits<InputIt>::value_type acc = *first;
    *d_first = acc;
    while (++first != last)
    {
        acc = op(std::move(acc), *first); // std::move since C++20
        *++d_first = acc;
    }
    return ++d_first;
}

참고 사항

acc LWG 이슈 539 의 해결로 인해 도입되었습니다. 결과를 직접 합산하는 방식(즉 * ( d_first + 2 ) = ( * first + * ( first + 1 ) ) + * ( first + 2 ) ; ) 대신 acc 를 사용하는 이유는 다음과 같은 유형이 일치하지 않을 경우 후자의 의미가 혼란스러울 수 있기 때문입니다:

  • InputIt 의 값 타입
  • OutputIt 의 쓰기 가능 타입(들)
  • operator + 또는 op 의 매개변수 타입들
  • operator + 또는 op 의 반환 타입

acc 는 계산의 각 단계에 대한 값을 저장하고 제공하는 중간 객체 역할을 합니다:

  • 그 타입은 InputIt 의 값 타입입니다
  • 그것은 d_first 에 기록됩니다
  • 그 값은 operator + 또는 op 에 전달됩니다
  • 그것은 operator + 또는 op 의 반환 값을 저장합니다
enum not_int { x = 1, y = 2 };
char i_array[4] = {100, 100, 100, 100};
not_int e_array[4] = {x, x, y, y};
int  o_array[4];
// 정상: operator+(char, char)를 사용하고 char 값을 int 배열에 할당함
std::partial_sum(i_array, i_array + 4, o_array);
// 오류: not_int 값을 int 배열에 할당할 수 없음
std::partial_sum(e_array, e_array + 4, o_array);
// 정상: 필요한 경우 변환을 수행함
// 1. char 타입의 "acc" 생성(값 타입)
// 2. char 인수가 long 곱셈에 사용됨(char -> long)
// 3. long 곱이 "acc"에 할당됨(long -> char)
// 4. "acc"가 "o_array"의 요소에 할당됨(char -> int)
// 5. 입력 범위의 나머지 요소를 처리하기 위해 2단계로 돌아감
std::partial_sum(i_array, i_array + 4, o_array, std::multiplies<long>{});

예제

#include <functional>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
int main()
{
    std::vector<int> v(10, 2); // v = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2}
    std::cout << "The first " << v.size() << " even numbers are: ";
    // 결과를 cout 스트림에 출력
    std::partial_sum(v.cbegin(), v.cend(), 
                     std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
    // 결과를 벡터 v에 다시 기록
    std::partial_sum(v.cbegin(), v.cend(),
                     v.begin(), std::multiplies<int>());
    std::cout << "The first " << v.size() << " powers of 2 are: ";
    for (int n : v)
        std::cout << n << ' ';
    std::cout << '\n';
}

출력:

The first 10 even numbers are: 2 4 6 8 10 12 14 16 18 20 
The first 10 powers of 2 are: 2 4 8 16 32 64 128 256 512 1024

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 242 C++98 op 부작용(side effects)을 가질 수 없었음 관련 범위를 수정할 수 없음
LWG 539 C++98 결과 평가와 할당이 유효하기 위해 필요한
타입 요구사항이 누락됨
추가됨

참고 항목

범위 내 인접한 요소들 간의 차이를 계산합니다
(함수 템플릿)
요소들의 범위를 합산하거나 접습니다
(함수 템플릿)
std::partial_sum 과 유사하며, i 번째 입력 요소를 i 번째 합계에 포함합니다
(함수 템플릿)
std::partial_sum 과 유사하며, i 번째 입력 요소를 i 번째 합계에서 제외합니다
(함수 템플릿)