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?
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?
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;
}
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:
std::reduce() - although you could, of course, implement more of them.util or stdx).PS - As @Ben notes, the Boost libraries have such container adapters for most <algorithm> functions... but not for std::reduce.