What are practical uses for STL's 'partial_sum'?

前端 未结 11 1732
耶瑟儿~
耶瑟儿~ 2021-02-04 03:47

What/where are the practical uses of the partial_sum algorithm in STL?

What are some other interesting/non-trivial examples or use-cases?

11条回答
  •  星月不相逢
    2021-02-04 04:38

    You could build a "moving sum" (precursor to a moving average):

    template 
    void moving_sum (const vector& in, int num, vector& out)
    {
        // cummulative sum
        partial_sum (in.begin(), in.end(), out.begin());
    
        // shift and subtract
        int j;
        for (int i = out.size() - 1; i >= 0; i--) {
            j = i - num;
            if (j >= 0)
                out[i] -= out[j];
        }    
    }
    

    And then call it with:

    vector v(10);
    // fill in v
    vector v2 (v.size());
    moving_sum (v, 3, v2);
    

提交回复
热议问题