Empirical
valsort_map.h
Go to the documentation of this file.
1 
18 #ifndef EMP_VALSORT_MAP_H
19 #define EMP_VALSORT_MAP_H
20 
21 #include <map>
22 
23 #include "../base/vector.h"
24 
25 namespace emp {
26 
27  template <class Key, // key_type
28  class T // mapped_type
29  // @CAO currently not handling special compare or alloc types.
30  >
31  class valsort_map {
32  public: // internal types
33  using key_type = Key;
34  using mapped_type = T;
35  using value_type = std::pair<const Key,T>;
36  private:
37  struct SortOrder {
38  bool operator()(const value_type & in1, const value_type & in2) {
39  if (in1.second == in2.second) return (in1.first < in2.first);
40  return in1.second < in2.second;
41  }
42  };
43 
44  std::map<Key,T> item_map;
45  std::set< value_type, SortOrder > val_set;
46 
47  public:
48  valsort_map() : item_map(), val_set() { ; }
49  valsort_map(const valsort_map &) = default;
50  valsort_map(valsort_map &&) = default;
51  ~valsort_map() { ; }
52 
53  size_t size() const { return item_map.size(); }
54 
55  const mapped_type & Get(key_type key) {
56  return item_map[key];
57  }
58 
59  void Set(key_type key, const mapped_type & value) {
60  auto map_it = item_map.find(key);
61  if (map_it != item_map.end()) {
62  val_set.erase(*map_it); // Erase the old pair from the set.
63  map_it->second = value; // Update the map
64  val_set.emplace(*map_it); // Place the new map entry into the set.
65  } else {
66  item_map[key] = value;
67  val_set.emplace(*item_map.find(key));
68  }
69  }
70 
71  // For now, don't change values using iterators, just look at them.
72  auto cbegin() { return item_map.cbegin(); }
73  auto cend() { return item_map.cend(); }
74  auto crbegin() { return item_map.crbegin(); }
75  auto crend() { return item_map.crend(); }
76 
77  // Add iterators that are ordred by value instead of key.
78  auto cvbegin() { return val_set.cbegin(); }
79  auto cvend() { return val_set.cend(); }
80  auto crvbegin() { return val_set.crbegin(); }
81  auto crvend() { return val_set.crend(); }
82 
83  };
84 }
85 
86 #endif
87 
88 
auto crend()
Definition: valsort_map.h:75
Key key_type
Definition: valsort_map.h:33
void Set(key_type key, const mapped_type &value)
Definition: valsort_map.h:59
auto cend()
Definition: valsort_map.h:73
Definition: valsort_map.h:31
auto cvend()
Definition: valsort_map.h:79
valsort_map()
Definition: valsort_map.h:48
auto crbegin()
Definition: valsort_map.h:74
auto crvend()
Definition: valsort_map.h:81
T mapped_type
Definition: valsort_map.h:34
std::pair< const Key, T > value_type
Definition: valsort_map.h:35
If we are in emscripten, make sure to include the header.
Definition: array.h:37
const mapped_type & Get(key_type key)
Definition: valsort_map.h:55
~valsort_map()
Definition: valsort_map.h:51
auto cbegin()
Definition: valsort_map.h:72
size_t size() const
Definition: valsort_map.h:53
auto cvbegin()
Definition: valsort_map.h:78
auto crvbegin()
Definition: valsort_map.h:80