Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <vector>
- #include <numeric>
- #include <type_traits>
- #include <algorithm>
- #include <stdexcept>
- #include <iostream>
- struct dataInType {
- double value; // what was voted on
- int votes; // how many times the value was voted on
- using value_type = double;
- bool operator>(const dataInType &rhs) const {
- return value > rhs.value;
- }
- bool operator<(const dataInType &rhs) const {
- return value < rhs.value;
- }
- value_type operator+(const dataInType &rhs) const {
- return value * votes + rhs.value* rhs.votes;
- }
- value_type operator+(value_type rhs) const {
- return value * votes + rhs;
- }
- value_type operator-(const dataInType &rhs) const {
- return value * votes - rhs.value * rhs.votes;
- }
- value_type operator-(value_type rhs) const {
- return value * votes - rhs;
- }
- operator value_type() const {
- return value * votes;
- }
- };
- std::ostream& operator<<(std::ostream &o, const dataInType &rhs) {
- o << '{' << rhs.value << ',' << rhs.votes << '}';
- return o;
- }
- /**
- * @param first
- * @param last
- * @return Unbiased sample standard deviation
- *
- * There is a bit of line noise here, but C++14 return-type deduction can fix it
- */
- template<typename RandIt>
- auto std_dev(RandIt first, RandIt last) -> typename std::decay<decltype(*first)>::type::value_type {
- using T = typename std::decay<decltype(*first)>::type;
- using value_type = typename T::value_type;
- auto size = std::distance(first, last);
- if (size < 2) {
- if (size == 1) {
- // This is an arbitrary decision
- return value_type(*first);
- }
- throw std::out_of_range ("Empty range");
- }
- auto avg = std::accumulate(first, last, value_type { }) / size;
- auto sum = std::accumulate(first, last, value_type(),
- [avg](value_type a, const T &x) {
- return a += (x - avg) * (x - avg);
- }
- );
- return std::sqrt(sum / (size - 1));
- }
- int main() {
- std::vector<dataInType> x = {
- {12.1, 4}, {6.2, 5}, {0.34, 12}, {8.0, 1},
- {6.7, 2}, {1.11, 17}, {0.65, 7}, {12.55, 8}
- };
- auto max = *std::max_element(x.begin(), x.end());
- auto stddev = std_dev(x.begin(), x.end());
- std::cout << "max = " << max << "\n"
- << "stddev = " << stddev << "\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement