Documentation of CSL
linear_map.h
1 // This file is part of MARTY.
2 //
3 // MARTY is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation, either version 3 of the License, or
6 // (at your option) any later version.
7 //
8 // MARTY is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with MARTY. If not, see <https://www.gnu.org/licenses/>.
15 
16  #pragma once
17 
18 #include <utility>
19 #include <vector>
20 
21 namespace csl {
22 
23 template<class Key, class Value>
24 class linear_map {
25 
26 public:
27  using iterator =
28  typename std::vector<std::pair<Key, Value>>::iterator;
29  using const_iterator =
30  typename std::vector<std::pair<Key, Value>>::const_iterator;
31 
32  auto size() const { return data.size(); }
33  bool empty() const { return data.empty(); }
34  auto begin() { return data.begin(); }
35  auto begin() const { return data.begin(); }
36  auto end() { return data.end(); }
37  auto end() const { return data.end(); }
38  auto cbegin() const { return data.begin(); }
39  auto cend() const { return data.end(); }
40 
41  iterator erase(iterator iter) {
42  size_t pos = std::distance(begin(), iter);
43  data.erase(iter);
44  return data.begin() + pos;
45  }
46  iterator find(Key const &value) {
47  auto first = data.begin();
48  const auto end = data.end();
49  while (first != end) {
50  if (first->first == value)
51  break;
52  ++first;
53  }
54  return first;
55  }
56  const_iterator find(Key const &value) const {
57  auto first = data.begin();
58  const auto end = data.end();
59  while (first != end) {
60  if (first->first == value)
61  break;
62  ++first;
63  }
64  return first;
65  }
66 
67  Value &operator[](Key const &key) {
68  auto pos = find(key);
69  if (pos == end()) {
70  data.push_back({key, Value()});
71  return data.back().second;
72  }
73  return pos->second;
74  }
75 
76 private:
77 
78  std::vector<std::pair<Key, Value>> data;
79 };
80 
81 }
Definition: linear_map.h:24
Namespace for csl library.
Definition: abreviation.h:34