Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdint>
- #include <iterator>
- #include <type_traits>
- template<typename RandomAccessIterator>
- auto average(RandomAccessIterator first, RandomAccessIterator last)
- -> long double
- {
- static_assert(std::is_integral<
- typename std::iterator_traits<RandomAccessIterator>::value_type
- >::value, "average only available for built-in integer types");
- auto size = std::distance(first, last);
- if (size == 0) return 0.0L;
- std::intmax_t accumulator = 0;
- long double res = 0.0L;
- while (first != last) {
- std::intmax_t tmp;
- if (__builtin_add_overflow(*first, accumulator, &tmp)) {
- res += static_cast<long double>(accumulator) / static_cast<long double>(size);
- accumulator = *first;
- } else {
- accumulator = tmp;
- }
- ++first;
- }
- res += static_cast<long double>(accumulator) / static_cast<long double>(size);
- return res;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement