Skip to content

Instantly share code, notes, and snippets.

@hnrck
Created July 13, 2020 08:30
Show Gist options
  • Save hnrck/f7c0f75bff09e792a8c96675e722fc87 to your computer and use it in GitHub Desktop.
Save hnrck/f7c0f75bff09e792a8c96675e722fc87 to your computer and use it in GitHub Desktop.
C++20 numeric accumulate implementation
#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
#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