Skip to content

Latest commit

 

History

History
65 lines (41 loc) · 1.26 KB

333.md

File metadata and controls

65 lines (41 loc) · 1.26 KB
Info

Example

#include <span>

constexpr std::array a = {1, 2, 3, 4, 5};
constexpr std::span s{a};

static_assert(s[0]==a[0]);

https://godbolt.org/z/T76csW9MM

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));

https://godbolt.org/z/4hYExTxdq

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));

https://godbolt.org/z/zff6qPcT5

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));

https://godbolt.org/z/1dx51dWeq