Empirical
map_utils.h
Go to the documentation of this file.
1 
11 #ifndef EMP_MAP_UTILS_H
12 #define EMP_MAP_UTILS_H
13 
14 #include <map>
15 #include <unordered_map>
16 
17 namespace emp {
18 
20  template <class MAP_T, class KEY_T>
21  inline bool Has( const MAP_T & in_map, const KEY_T & key ) {
22  return in_map.find(key) != in_map.end();
23  }
24 
25 
28  template <class MAP_T, class KEY_T>
29  inline auto Find( const MAP_T & in_map, const KEY_T & key, const typename MAP_T::mapped_type & dval) {
30  auto val_it = in_map.find(key);
31  if (val_it == in_map.end()) return dval;
32  return val_it->second;
33  }
34 
35 
38  template <class MAP_T, class KEY_T>
39  inline const auto & FindRef( const MAP_T & in_map, const KEY_T & key, const typename MAP_T::mapped_type & dval) {
40  auto val_it = in_map.find(key);
41  if (val_it == in_map.end()) return dval;
42  return val_it->second;
43  }
44 
45 
46  // The following two functions are from:
47  // http://stackoverflow.com/questions/5056645/sorting-stdmap-using-value
48 
50  template<typename A, typename B> constexpr std::pair<B,A> flip_pair(const std::pair<A,B> &p)
51  {
52  return std::pair<B,A>(p.second, p.first);
53  }
54 
56  template<typename A, typename B> std::multimap<B,A> flip_map(const std::map<A,B> &src)
57  {
58  std::multimap<B,A> dst;
59  for (const auto & x : src) dst.insert( flip_pair(x) );
60  return dst;
61  }
62 }
63 
64 #endif
std::multimap< B, A > flip_map(const std::map< A, B > &src)
Take an std::map<A,B> and return the flipped map (now multimap to be safe): std::multimap<B,A>
Definition: map_utils.h:56
auto Find(const MAP_T &in_map, const KEY_T &key, const typename MAP_T::mapped_type &dval)
Definition: map_utils.h:29
constexpr std::pair< B, A > flip_pair(const std::pair< A, B > &p)
Take an std::pair<A,B> and return the flipped pair std::pair<B,A>
Definition: map_utils.h:50
bool Has(const MAP_T &in_map, const KEY_T &key)
Take any map type, and run find to determine if a key is present.
Definition: map_utils.h:21
If we are in emscripten, make sure to include the header.
Definition: array.h:37
const auto & FindRef(const MAP_T &in_map, const KEY_T &key, const typename MAP_T::mapped_type &dval)
Definition: map_utils.h:39