Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <cassert>
- #include <optional>
- #include <string_view>
- #include <utility>
- #include <vector>
- using namespace std;
- template <typename InputIt, typename OutSum, typename OutSqSum, typename OutMax>
- void ComputeStatistics(InputIt first,
- InputIt last,
- OutSum& out_sum,
- OutSqSum& out_sq_sum,
- OutMax& out_max) {
- using Elem = std::decay_t<decltype(*first)>;
- constexpr bool need_sum = !is_same_v<OutSum, const nullopt_t>;
- constexpr bool need_sq_sum = !is_same_v<OutSqSum, const nullopt_t>;
- constexpr bool need_max = !is_same_v<OutMax, const nullopt_t>;
- optional<Elem> sum, sq_sum, max_elem;
- size_t count = 0;
- for (auto it = first; it != last; ++it, ++count) {
- if constexpr (need_sum) {
- !sum ? sum = *it : *sum += *it;
- }
- if constexpr (need_sq_sum) {
- !sq_sum ? sq_sum = *it * *it : *sq_sum += *it * *it;
- }
- if constexpr (need_max) {
- !max_elem ? max_elem = *it : max_elem = max(*max_elem, *it);
- }
- }
- if constexpr (need_sum) {
- if (sum) {
- out_sum = *sum;
- }
- }
- if constexpr (need_sq_sum) {
- if (sq_sum) {
- out_sq_sum = *sq_sum;
- }
- }
- if constexpr (need_max) {
- if (max_elem) {
- out_max = *max_elem;
- }
- }
- }
- struct OnlySum {int value;};
- OnlySum operator+(OnlySum l, OnlySum r) {return {l.value + r.value};}
- OnlySum& operator+=(OnlySum& l, OnlySum r) {return l = l + r;}
- int main() {
- vector input = {1, 2, 3, 4, 5, 6};
- int sq_sum;
- std::optional<int> max;
- ComputeStatistics(input.begin(), input.end(), nullopt, sq_sum, max);
- assert(sq_sum == 91 && max && *max == 6);
- vector<OnlySum> only_sum_vector = {{100}, {-100}, {20}};
- OnlySum sum;
- ComputeStatistics(only_sum_vector.begin(), only_sum_vector.end(), sum, nullopt, nullopt);
- assert(sum.value == 20);
- }
Advertisement
Add Comment
Please, Sign In to add comment