Namespaces
Variants

std::partial_sum

From cppreference.com
 
 
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy, ranges::sort, ...
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
(C++11)    

Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
(C++11)
(C++17)
Lexicographical comparison operations
Permutation operations


 
 
Defined in header <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)

Computes the partial sums of elements in the source range [first, last), the results are stored in the destination range [d_first, d_last), where d_last is std::next(d_first, std::distance(first, last)).

  • If the source range is empty, no sum will be computed.
  • Otherwise, std::distance(first, last) sums will be computed.

Let

  • T be the value type of InputIt, and
  • add_op be the add operation, it is operator+(until C++20)an object of type std::plus<>(since C++20) for overload (1), or op for overload (2).

If the source range is not empty, performs the following operations in order:

  1. Initializes the accumulator acc (of type T) with the initial value *first.
  2. Assigns acc to *d_first.
  3. For each iterator iter in [std::next(first), last) and the corresponding iterator d_iter in the destination range in order, performs the following operations in order:
a) acc is modified by acc = add_op(acc, *iter)(until C++20)acc = add_op(std::move(acc), *iter)(since C++20).
b) The result of the assignment is assigned to *d_iter.

If any of the following conditions is satisfied, the program is ill-formed:

  • T is not constructible from *first.
  • acc is not writable to d_first.
  • The result of the assignment expression in step 3a is not implicitly convertible to T.

If any of the following conditions is satisfied, the behavior is undefined:

  • add_op modifies any element of the source range or the destination range.
  • add_op invalidates any iterator or subrange in [first, last] or [d_first, d_last].

Parameters

first, last - the pair of iterators defining the source range
d_first - the beginning of the destination range
op - binary operation function object that will be applied.

The signature of the function should be equivalent to the following:

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

The signature does not need to have const &.
The type Type1 must be such that an object of type std::iterator_traits<InputIt>::value_type can be implicitly converted to Type1. The type Type2 must be such that an object of type InputIt can be dereferenced and then implicitly converted to Type2. The type Ret must be such that an object of type InputIt can be dereferenced and assigned a value of type Ret. ​

Type requirements
-
InputIt must meet the requirements of LegacyInputIterator.
-
OutputIt must meet the requirements of LegacyOutputIterator.

Return value

The past-the-end iterator of the destination range (i.e. d_last).

Complexity

Given N as std::distance(first, last):

1) Exactly N-1 applications of operator+.
2) Exactly N-1 applications of op.

Notes

acc was introduced because of the resolution of LWG issue 539. The reason of using acc rather than directly summing up the results (i.e. *(d_first + 2) = (*first + *(first + 1)) + *(first + 2);) is because the semantic of the latter is confusing if the following types mismatch:

  • the value type of InputIt
  • the writable type(s) of OutputIt
  • the types of the parameters of add_op
  • the return type of add_op

acc serves as the intermediate object to store and provide the values for each step of the computation:

  • Its type is the value type of InputIt.
  • It is written to d_first.
  • Its value is passed to add_op.
  • It stores the return value of add_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];

// OK: uses operator+(char, char) and assigns char values to int array
std::partial_sum(i_array, i_array + 4, o_array);

// Error: cannot assign not_int values to int array
std::partial_sum(e_array, e_array + 4, o_array);

// OK: performs conversions when needed
// 1. creates “acc” of type char (the value type)
// 2. the char arguments are used for long multiplication (char -> long)
// 3. the long product is assigned to “acc” (long -> char)
// 4. “acc” is assigned to an element of “o_array” (char -> int)
// 5. go back to step 2 to process the remaining elements in the input range
std::partial_sum(i_array, i_array + 4, o_array, std::multiplies<long>{});

Possible implementation

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;
    
    // or, since 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;
}

Example

#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: ";
    // write the result to the cout stream
    std::partial_sum(v.cbegin(), v.cend(), 
                     std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
    
    // write the result back to the vector 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';
}

Output:

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

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 242 C++98 add_op could not have side effects it cannot modify the ranges involved
LWG 539 C++98 the type requirements needed for the result
evaluations and assignments to be valid were missing
added

See also

computes the differences between adjacent elements in a range
(function template) [edit]
sums up or folds a range of elements
(function template) [edit]
similar to std::partial_sum, includes the ith input element in the ith sum
(function template) [edit]
similar to std::partial_sum, excludes the ith input element from the ith sum
(function template) [edit]