Cumulative product of an array: std::accumulate vs loop

  accumulate, c++

Let’s say I want to compute the cumulative product of the first k elements of an array.

int arr[8] = {3, 5, 7, 4, 8, 9, 1, 2};
int k = 3;

Which one is the best option?

Option 1. Ordinary for loop

int result = 1;
for (size_t i = 0; i < k; ++i) {
    result *= arr[i];
}

Option 2. Accumulate

result = std::accumulate(std::begin(arr),
                         std::begin(arr) + k,
                         1,
                         [](const int& x, const int &y) { return x*y; });

I am especially interested in cases where k is small, for example k = 3 or k = 4. Is the fancy C++11 way of doing things actually worth it in this case?

Source: Windows Questions C++

LEAVE A COMMENT