-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculate_mean.cpp
More file actions
38 lines (33 loc) · 868 Bytes
/
calculate_mean.cpp
File metadata and controls
38 lines (33 loc) · 868 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <type_traits>
template
<
typename InputItr,
std::enable_if_t<std::is_arithmetic<typename std::decay_t<InputItr>::value_type>::value>*
= nullptr
>
constexpr inline auto sum(InputItr first, InputItr last) noexcept
{
using ValType = std::decay_t<decltype(*first)>;
auto result{static_cast<ValType>(0)};
while(first != last){result += *(first++);}
return result;
}
#include <iterator>
template
<
typename InputItr,
std::enable_if_t<std::is_arithmetic<typename std::decay_t<InputItr>::value_type>::value>*
= nullptr
>
constexpr inline auto mean(InputItr first, InputItr last) noexcept
{
return sum(first, last) / std::distance(first, last);
}
#include <iostream>
#include <vector>
int main()
{
//This test program calculates mean of data.
std::vector<double> data{1, 2, 3, 4, 5};
std::cout << mean(data.begin(), data.end()) << std::endl;
}