Understanding std::accumulate

前端 未结 5 2027
轮回少年
轮回少年 2020-12-23 11:11

I want to know why std::accumulate (aka reduce) 3rd parameter is needed. For those who do not know what accumulate is, it\'s used like so:

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 11:38

    The way things are, it is annoying for code that knows for sure a range isn't empty and that wants to start accumulating from the first element of the range on. Depending on the operation that is used to accumulate with, it's not always obvious what the 'zero' value to use is.

    If on the other hand you only provide a version that requires non-empty ranges, it's annoying for callers that don't know for sure that their ranges aren't empty. An additional burden is put on them.

    One perspective is that the best of both worlds is of course to provide both functionality. As an example, Haskell provides both foldl1 and foldr1 (which require non-empty lists) alongside foldl and foldr (which mirror std::transform).

    Another perspective is that since the one can be implemented in terms of the other with a trivial transformation (as you've demonstrated: std::transform(std::next(b), e, *b, f) -- std::next is C++11 but the point still stands), it is preferable to make the interface as minimal as it can be with no real loss of expressive power.

提交回复
热议问题