Euphoria
stdutils.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <map>
4 #include <algorithm>
5 
6 #include "assert/assert.h"
7 
8 
9 namespace eu::core
10 {
11  template <typename K, typename V>
12  std::vector<K>
13  get_keys(const std::map<K, V>& m)
14  {
15  std::vector<K> r;
16  for(const auto& x: m)
17  {
18  r.push_back(x.first);
19  }
20  return r;
21  }
22 
23  template <typename K>
24  std::vector<K>
25  get_sorted(const std::vector<K>& k)
26  {
27  auto s = k;
28  std::sort(s.begin(), s.end());
29  return s;
30  }
31 
32  template <typename K, typename V>
33  std::vector<std::string>
34  get_keys_as_strings(const std::map<K, V>& m)
35  {
36  std::vector<std::string> strings;
37  for(const auto& x: m)
38  {
39  strings.push_back(fmt::format("{}", x.first));
40  }
41  return strings;
42  }
43 
44  template <typename T>
45  bool
46  swap_back_and_erase_object(T what, std::vector<T>* from)
47  {
48  ASSERT(from);
49  using Vec = std::vector<T>;
50  typename Vec::iterator result
51  = std::find(from->begin(), from->end(), what);
52  if(result == from->end())
53  {
54  return false;
55  }
56 
57  typename Vec::iterator last = from->end();
58  --last; // point to a valid entry
59  std::swap(*result, *last);
60  from->pop_back();
61 
62  return true;
63  }
64 
65  template <typename T, typename TFunc>
66  void
67  remove_matching(std::vector<T>* v, TFunc condition)
68  {
69  v->erase(std::remove_if(v->begin(), v->end(), condition), v->end());
70  }
71 
72  template <typename T, typename TFunc>
73  typename std::vector<T>::iterator
74  find_first(std::vector<T>& v, TFunc condition)
75  {
76  for(auto iter = v.begin(); iter != v.end(); iter++)
77  {
78  if(condition(*iter))
79  {
80  return iter;
81  }
82  }
83 
84  return v.end();
85  }
86 
87 
88  // convert a enum class to it's underlying (int) type
89  // src: https://twitter.com/idoccor/status/1314664849276899328
90  template<typename E>
91  constexpr typename std::underlying_type<E>::type
92  base_cast(E e) noexcept
93  {
94  return static_cast<typename std::underlying_type<E>::type>(e);
95  }
96 
97 }
98 
#define ASSERT(x)
Definition: assert.h:29
constexpr std::underlying_type< E >::type base_cast(E e) noexcept
Definition: stdutils.h:92
std::vector< K > get_keys(const std::map< K, V > &m)
Definition: stdutils.h:13
std::vector< std::string > get_keys_as_strings(const std::map< K, V > &m)
Definition: stdutils.h:34
void remove_matching(std::vector< T > *v, TFunc condition)
Definition: stdutils.h:67
bool swap_back_and_erase_object(T what, std::vector< T > *from)
Definition: stdutils.h:46
std::vector< K > get_sorted(const std::vector< K > &k)
Definition: stdutils.h:25
bool find(const std::string &target, const std::string &search)
Definition: findstring.cc:8
std::vector< T >::iterator find_first(std::vector< T > &v, TFunc condition)
Definition: stdutils.h:74