C++ std::reduce with array

Viewed 1931
int arr1[5] = { 1,2,3,4,5 };
int sum = reduce(arr1[0], arr1[5]);

I wrote this code to use the std::reduce function with an integer array. How am I supposed to define the beginning and end of the array?

2 Answers

Use std::cbegin() and std::cend() on the array:

#include <iostream>
#include <numeric>
int main(){
    int arr1[5] = { 1,2,3,4,5 };
    int sum = std::reduce(std::cbegin(arr1), std::cend(arr1));
    std::cout << sum;
}

Demo

If you often use <algorithm> algorithms on containers, you could write something like:

template <typename Container>
constexpr typename Container::value_type 
reduce(const Container& container) {
   return std::reduce(std::cbegin(container), std::cend(container));
}

Then you can just:

int arr1[5] = { 1,2,3,4,5 };
auto sum = reduce(arr1);

This has several detriments, including:


PS - As @Ben notes, the Boost libraries have such container adapters for most <algorithm> functions... but not for std::reduce.

Related