-
Notifications
You must be signed in to change notification settings - Fork 0
/
index_bimap.hpp
70 lines (50 loc) · 1.42 KB
/
index_bimap.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#pragma once
#include <map>
#include <iostream>
/////////////////////////////////////
// custom bimap with size_t indexes
template <typename L>
class index_bimap {
std::map<L, std::size_t> _left;
std::map<std::size_t, L> _right;
public:
inline void insert(const L& l, const std::size_t& r) {
_left[l] = r;
_right[r] = l;
}
inline const std::size_t left(const L& l) const { return _left.at(l); }
inline const L right(const std::size_t& r) const { return _right.at(r); }
inline const std::size_t ensure(const L& l) {
try {
return _left.at(l);
} catch (std::out_of_range& ex) {
std::size_t i = _left.size();
_left[l] = i;
_right[i] = l;
return i;
}
}
inline const std::size_t size() { return _left.size(); }
// serialize
inline const bool serialize(std::ostream& outs=std::cout) {
// write out L's in ascending index order
if (outs.good()) {
for (auto const& entry: _right) {
outs << entry.first << "\t" << entry.second << "\n"; // avoid endl flush!
}
return true;
} else return false;
}
// de-serialize
inline const bool deserialize(std::istream& ins=std::cin) {
if (ins.good()) {
std::size_t idx;
L feature;
_left.clear();
_right.clear();
while (ins >> idx >> feature)
insert(feature, idx);
return true;
} else return false;
}
};