What are the requirements for functor accumulation?

I wrote the answer here: https://stackoverflow.com/a/166608/ which uses accumulate.

The functor must be binary with a signature like: Ret op(const auto& a, const auto& b)but:

No signature required const &

The requirement for a binary functor is that it:

You cannot invalidate any iterators, including trailing iterators, or modify any elements of the range involved.

When the accumulated object itself is a container, I am unclear regarding the requirements for the functor. For example, is something like that allowed?

const auto range = { 0, 1, 2, 3 };
const auto Ret = accumulate(cbegin(range), cend(range), vector<int>(), [](auto& a, const auto& b){
    a.push_back(b);
    return a;
});

Yes, I admit that this is just a copy, I am not asking for a better solution, which I ask about the validity of this decision.

+4
1

, , cppreference - :

[first, last], binary_­op .

accumulate :

template <class InputIterator, class T>
T accumulate(InputIterator first, InputIterator last, T init);

template <class InputIterator, class T, class BinaryOperation>
T accumulate(InputIterator first, InputIterator last, T init, BinaryOperation binary_op);

, , [first, last].

, , .
, , , binary_op.
, accumulate . .

+3

Source: https://habr.com/ru/post/1679005/


All Articles