Created
July 13, 2020 08:30
-
-
Save hnrck/f7c0f75bff09e792a8c96675e722fc87 to your computer and use it in GitHub Desktop.
C++20 numeric accumulate implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef MY_STD_ACCUMULATE_H | |
#define MY_STD_ACCUMULATE_H | |
namespace my_std { | |
template<class InputIt, class T, class BinaryOperation> | |
inline auto accumulate(InputIt first, InputIt last, T init, BinaryOperation op) -> T { | |
for (; first < last; ++first) { | |
init = op(std::move(init), *first); | |
} | |
return init; | |
} | |
template<class InputIt, class T> | |
inline auto accumulate(InputIt first, InputIt last, T init) -> T { | |
return my_std::accumulate(first, last, init, [](unsigned int a, unsigned int b) { return a + b; }); | |
} | |
} | |
#endif // MY_STD_ACCUMULATE_H |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <functional> | |
#include <vector> | |
#include "accumulate.h" | |
int main() { | |
constexpr auto MIN = 1u; | |
constexpr auto MAX = 10u; | |
auto v = std::vector<unsigned int>{}; | |
for (auto i = MIN; i <= MAX; ++i) { | |
v.push_back(i); | |
} | |
auto ss = 0u; | |
ss = my_std::accumulate(std::begin(v), std::end(v), ss); | |
std::cout << ss << std::endl; | |
auto sp = 1u; | |
sp = my_std::accumulate(std::begin(v), std::end(v), sp, std::multiplies<>()); | |
std::cout << sp << std::endl; | |
const auto dash_fold = [=](std::string s, int x) { return std::move(s) + ", " + std::to_string(x); }; | |
auto sd = std::to_string(*std::begin(v)), md = std::to_string(*std::begin(v)); | |
sd = std::move(my_std::accumulate(std::next(std::begin(v)), std::end(v), sd, dash_fold)); | |
std::cout << sd << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment