Understanding std::accumulate

前端 未结 5 2040
轮回少年
轮回少年 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:31

    If you wanted accumulate(V.begin()+1, V.end(), V.begin()) you could just write that. But what if you thought v.begin() might be v.end() (i.e. v is empty)? What if v.begin() + 1 is not implemented (because v only implements ++, not generized addition)? What if the type of the accumulator is not the type of the elements? Eg.

    std::accumulate(v.begin(), v.end(), 0, [](long count, char c){
       return isalpha(c) ? count + 1 : count
    });
    

提交回复
热议问题