Example
#include <span>
constexpr std::array a = {1, 2, 3, 4, 5};
constexpr std::span s{a};
static_assert(s[0]==a[0]);
Puzzle
-
Can you implement sum using std algorithms which takes the span?
- Double points for finding multiple algorithms to achieve it
constexpr std::array a = {1, 2, 3, 4, 5};
constexpr std::span s{a};
//TODO sum
static_assert(15 == sum(s));
Solutions
constexpr std::array a = {1, 2, 3, 4, 5};
constexpr std::span s{a};
constexpr auto sum = []([[maybe_unused]] auto s) {
return std::reduce(s.begin(), s.end(), 0);
};
static_assert(15 == sum(s));
constexpr std::array a = {1, 2, 3, 4, 5};
constexpr std::span s{a};
constexpr auto sum = []([[maybe_unused]] auto s) {
return std::accumulate(std::cbegin(s), std::cend(s), 0);
};
static_assert(15 == sum(s));