Elements 6.1.2
A C++ base framework for the Euclid Software.
Loading...
Searching...
No Matches
UnitTestExample.cpp
Go to the documentation of this file.
1
23
24#include <algorithm> // sort
25#include <numeric> // accumulate
26#include <vector> // vector
27
29
30using std::vector;
31
32namespace Elements {
33namespace 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
defines the base Elements exception class
T accumulate(T... args)
T begin(T... args)
double average(const std::vector< int > &v)
Returns a particular version of the "average" of the vector values.
Elements base exception class.
Definition: Exception.h:47
T end(T... args)
T size(T... args)
T sort(T... args)