Evoplex  0.2.1
utils.h
1 /* Evoplex <https://evoplex.org>
2  * Copyright (C) 2016-present - Marcos Cardinot <marcos@cardinot.net>
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef UTILS_H
18 #define UTILS_H
19 
20 #include <QHash>
21 #include <map>
22 #include <math.h>
23 #include <unordered_set>
24 #include <vector>
25 
26 #include "prg.h"
27 
28 namespace evoplex
29 {
30 namespace Utils
31 {
32  template <class T>
33  void deleteAndShrink(std::vector<T*>& v) {
34  qDeleteAll(v);
35  v.clear();
36  std::vector<T*> ve;
37  ve.swap(v);
38  }
39 
40  template <class T>
41  void clearAndShrink(std::vector<T>& v) {
42  v.clear();
43  v.shrink_to_fit();
44  }
45 
46  template <typename T, class C>
47  void deleteAndShrink(QHash<T, C*>& h) {
48  qDeleteAll(h);
49  h.clear();
50  h.squeeze();
51  }
52 
53  template <typename T, class C>
54  void deleteAndShrink(std::map<T, C*>& m) {
55  for (auto& i : m) {
56  delete i.second;
57  i.second = nullptr;
58  }
59  m.clear();
60  }
61 
62  template <class C>
63  void deleteAndShrink(std::unordered_set<C*>& s) {
64  for (C* c : s) {
65  delete c;
66  c = nullptr;
67  }
68  s.clear();
69  }
70 
76  template <class C, class T>
77  int indexOf(const C& container, const T& val) {
78  Q_ASSERT(container.size() < INT32_MAX);
79  const int s = static_cast<int>(container.size());
80  for (int idx = 0; idx < s; ++idx) {
81  if (container.at(idx) == val) return idx;
82  }
83  return -1;
84  }
85 
91  template <typename T>
92  void shuffle(std::vector<T>& vector, PRG* prg) {
93  size_t n = vector.size();
94  // While there remain elements to shuffle…
95  while (n) {
96  // Pick a remaining element…
97  const size_t i = std::floor(prg->uniform() * n--);
98  // And swap it with the current element.
99  const T t = vector[n];
100  vector[n] = vector[i];
101  vector[i] = t;
102  }
103  }
104 
105 } // utils
106 } // evoplex
107 #endif // UTILS_H
Definition: abstractgraph.h:29