emilib
list_set.hpp
1 // By Emil Ernerfeldt 2014-2016
2 // LICENSE:
3 // This software is dual-licensed to the public domain and under the following
4 // license: you are granted a perpetual, irrevocable license to copy, modify,
5 // publish, and distribute this file as you see fit.
6 
7 #pragma once
8 
9 #include <vector>
10 
11 namespace emilib {
12 
14 template<typename T>
16 {
17  constexpr bool operator()(const T &lhs, const T &rhs) const
18  {
19  return lhs == rhs;
20  }
21 };
22 
24 template<typename KeyT, typename EqT = ListSetEqualTo<KeyT>>
25 class ListSet
26 {
27 public:
28  using List = std::vector<KeyT>;
29 
30  using size_type = size_t;
31  using value_type = KeyT;
32  using reference = KeyT&;
33  using const_reference = const KeyT&;
34  using iterator = typename List::iterator;
35  using const_iterator = typename List::const_iterator;
36 
37  iterator begin() { return _list.begin(); }
38  iterator end() { return _list.end(); }
39  const_iterator begin() const { return _list.begin(); }
40  const_iterator end() const { return _list.end(); }
41 
42  size_t size() const { return _list.size(); }
43  bool empty() const { return _list.empty(); }
44 
45  int count(const KeyT& key) const
46  {
47  for (auto&& k : *this) {
48  if (_eq(k, key)) {
49  return 1;
50  }
51  }
52  return 0;
53  }
54 
55  bool insert(const KeyT& key)
56  {
57  for (auto&& k : *this) {
58  if (_eq(k, key)) {
59  return false; // like std::set we do not insert if we already have it
60  }
61  }
62  _list.push_back(key);
63  return true;
64  }
65 
68  {
69  _list.shrink_to_fit();
70  }
71 
72  void clear() { _list.clear(); }
73 
74 private:
75  List _list;
76  EqT _eq;
77 };
78 
79 } // namespace emilib
Linear lookup set for quick lookups among few values.
Definition: list_set.hpp:25
like std::equal_to but no need to #include <functional>
Definition: list_set.hpp:15
void shrink_to_fit()
Frees unnecessary memory.
Definition: list_set.hpp:67
Definition: coroutine.hpp:18