Skip to content

Instantly share code, notes, and snippets.

@bananu7
Created September 24, 2014 12:25
Show Gist options
  • Save bananu7/c14ee42627d1e7d327a1 to your computer and use it in GitHub Desktop.
Save bananu7/c14ee42627d1e7d327a1 to your computer and use it in GitHub Desktop.
template<typename T>
auto accumulate(T const& xs,
typename std::iterator_traits<decltype(begin(xs))>::value_type const& v)
-> decltype(std::plus<typename std::iterator_traits<decltype(begin(xs))>::value_type>(*std::begin(xs), *std::begin(xs)))
{
return std::accumulate(std::begin(xs), std::end(xs), v);
}
template<typename T, typename F>
auto accumulate(T const& xs,
typename std::iterator_traits<decltype(begin(xs))>::value_type const& v,
F&& f)
-> decltype(f(*std::begin(xs), *std::begin(xs)))
{
return std::accumulate(std::begin(xs), std::end(xs), v, std::forward<F>(f));
}
template<typename T>
auto accumulate1(T const& xs)
-> decltype(
std::declval<
std::plus<
typename std::iterator_traits<decltype(begin(xs))>::value_type
>
>()
(*std::begin(xs), *std::begin(xs))
)
{
if (xs.empty()) {
throw std::invalid_argument("Collection empty");
}
return std::accumulate(std::begin(xs) + 1, std::end(xs), *std::begin(xs));
}
template<typename T, typename F>
auto accumulate1(T const& xs, F&& f)
-> decltype(f(*std::begin(xs), *std::begin(xs)))
{
if (xs.empty()) {
throw std::invalid_argument("Collection empty");
}
return std::accumulate(std::begin(xs) + 1, std::end(xs), *std::begin(xs), f);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment