forpy 2

checks.h
Go to the documentation of this file.
1 /* Author: Christoph Lassner */
2 #pragma once
3 #ifndef FORPY_UTIL_CHECKS_H_
4 #define FORPY_UTIL_CHECKS_H_
5
6 #include <algorithm>
7 #include <functional>
8 #include <limits>
9 #include <type_traits>
10 #include <vector>
11
12 #include "../global.h"
13
14 namespace forpy {
15
19 template <typename T>
20 static bool safe_pos_sum_lessoe_than(const std::vector<T> &vec,
21 const T &limit) {
22 if (!std::is_arithmetic<T>()) {
23 // This case should've been already detected at compile time because
24 // of the use of std::numeric_limits in the function later on, but
25 // better be safe.
26 throw ForpyException(
27 "The safe_pos_sum_lessoe_than function can "
28 "only be called for arithmetic type vectors.");
29 }
30 T sum_so_far = static_cast<T>(0);
31 for (size_t i = 0; i < vec.size(); ++i) {
32 if (vec[i] < static_cast<T>(0) || limit - vec[i] < sum_so_far) {
33 return false;
34 } else {
35 sum_so_far += vec[i];
36 }
37 }
38 return true;
39 };
40
45 template <typename T>
46 static bool safe_pos_sum_lessoe_than(const std::vector<T> &vec1,
47 const std::vector<T> &vec2,
48 const T &limit) {
49 std::vector<T> joined;
50 joined.insert(joined.end(), vec1.begin(), vec1.end());
51 joined.insert(joined.end(), vec2.begin(), vec2.end());
52 return safe_pos_sum_lessoe_than(joined, limit);
53 };
54
59 template <typename T>
60 static bool safe_pos_sum_lessoe_than(const std::vector<T> &vec) {
61 return safe_pos_sum_lessoe_than(vec, std::numeric_limits<T>::max());
62 };
63
68 template <typename T>
69 static bool safe_pos_sum_lessoe_than(const std::vector<T> &vec1,
70 const std::vector<T> &vec2) {
71 return safe_pos_sum_lessoe_than(vec1, vec2, std::numeric_limits<T>::max());
72 };
73
77 #pragma clang diagnostic push
78 #pragma clang diagnostic ignored "-Wunused-function"
79 static bool check_elem_ids_ok(const size_t &n_samples,
80 const std::vector<size_t> &elem_ids) {
81 return elem_ids.end() ==
82 std::find_if(elem_ids.begin(), elem_ids.end(),
83 std::bind2nd(std::greater_equal<size_t>(), n_samples));
84 }
85 #pragma clang diagnostic pop
86
87 }; // namespace forpy
88 #endif // FORPY_UTIL_CHECKS_H_
forpy::check_elem_ids_ok
static bool check_elem_ids_ok(const size_t &n_samples, const std::vector< size_t > &elem_ids)
Tests whether all element ids are valid.
Definition: checks.h:79
forpy
Definition: fastdprov.h:13
forpy::safe_pos_sum_lessoe_than
static bool safe_pos_sum_lessoe_than(const std::vector< T > &vec, const T &limit)
Tests whether the sum of all elements in vec is less than limit.
Definition: checks.h:20
forpy::ForpyException
Definition: global.h:91