Elements  5.10
A C++ base framework for the Euclid Software.
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
UnitTestExample.cpp
Go to the documentation of this file.
1 
23 
24 #include <numeric> // accumulate
25 #include <algorithm> // sort
26 #include <vector> // vector
27 
29 
30 using std::vector;
31 
32 namespace Elements {
33 namespace Examples {
34 
36 
37  double result = 0.0;
38  auto size = v.size();
39  // Throw an exception if the number of vector elements is null!
40  if (size == 0) {
41  throw Exception() << "Input vector has no element!"; // can be removed to feed a unit test exercise
42  }
43 
44  // We check if we have enough numbers to compute the median
45  // if (size - 5 > 0) { // example mistake to feed a unit test exercise
46  if (size > 5) {
47  //
48  vector<int> ordered { v.begin(), v.end() };
49  std::sort(ordered.begin(), ordered.end());
50  if (size % 2 == 0) {
51  result = (ordered[size / 2 - 1] + ordered[size / 2]) / 2.;
52  } else {
53  result = ordered[size / 2];
54  }
55 
56  } else {
57  // If we have less than 5 numbers we compute the mean
58  // auto sum = std::accumulate(v.begin(), v.end(), 0); // example mistake to feed a unit test exercise
59  auto sum = std::accumulate(v.begin(), v.end(), 0.); // example mistake to feed a unit test exercise
60 
61  result = static_cast<double>(sum) / static_cast<double>(size);
62  }
63 
64  return result;
65 }
66 
67 } // namespace Examples
68 } // namespace Elements
double average(const std::vector< int > &v)
Returns a particular version of the &quot;average&quot; of the vector values.
T end(T...args)
T size(T...args)
STL class.
Elements base exception class.
Definition: Exception.h:46
T begin(T...args)
T sort(T...args)
T accumulate(T...args)
defines the base Elements exception class