Elements
6.2
A C++ base framework for the Euclid Software.
ElementsExamples
src
lib
default
UnitTestExample.cpp
Go to the documentation of this file.
1
22
#include "
ElementsExamples/UnitTestExample.h
"
23
24
#include <algorithm>
// sort
25
#include <numeric>
// accumulate
26
#include <vector>
// vector
27
28
#include "
ElementsKernel/Exception.h
"
29
30
using
std::vector
;
31
32
namespace
Elements
{
33
namespace
Examples {
34
35
double
UnitTestExample::average
(
const
vector<int>
& v) {
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
std::vector
STL class.
std::vector::size
T size(T... args)
std::sort
T sort(T... args)
Elements::Examples::UnitTestExample::average
double average(const std::vector< int > &v)
Returns a particular version of the "average" of the vector values.
Definition:
UnitTestExample.cpp:35
Exception.h
defines the base Elements exception class
Elements::Exception
Elements base exception class.
Definition:
Exception.h:47
std::accumulate
T accumulate(T... args)
std::vector::begin
T begin(T... args)
UnitTestExample.h
std::vector::end
T end(T... args)
Elements
Definition:
callBackExample.h:35
Generated by
1.8.17