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

前端 未结 11 1700
耶瑟儿~
耶瑟儿~ 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:40

    You can use it to generate a monotonically increasing sequence of numbers. For example, the following generates a vector containing the numbers 1 through 42:

    std::vector v(42, 1);
    std::partial_sum(v.begin(), v.end(), v.begin());
    

    Is this an everyday use case? Probably not, though I've found it useful on several occasions.

    You can also use std::partial_sum to generate a list of factorials. (This is even less useful, though, since the number of factorials that can be represented by a typical integer data type is quite limited. It is fun, though :-D)

    std::vector v(10, 1);
    std::partial_sum(v.begin(), v.end(), v.begin());
    std::partial_sum(v.begin(), v.end(), v.begin(), std::multiplies());
    

提交回复
热议问题