-
Notifications
You must be signed in to change notification settings - Fork 4
/
MapID.hpp
86 lines (71 loc) · 1.48 KB
/
MapID.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#ifndef _MOURISL_MAPID
#define _MOURISL_MAPID
#include <map>
#include <vector>
#include <stdint.h>
// This class that maps of arbitrary object to numeric ID in range of [0, n)
template <class T>
class MapID
{
private:
std::map<T, size_t> _toNumId ;
std::vector<T> _toOrigElem ;
public:
MapID() {}
~MapID() {}
// @return: mapped id. Return the
size_t Add(const T &elem)
{
if (_toNumId.find(elem) == _toNumId.end())
{
uint64_t id = _toNumId.size() ;
_toNumId[elem] = id ;
_toOrigElem.push_back(elem) ;
return id ;
}
else
return _toNumId[elem] ;
}
size_t Map(const T &elem)
{
return _toNumId[elem] ;
}
bool IsIn(const T &elem)
{
return _toNumId.find(elem) != _toNumId.end() ;
}
// Map to original value
T Inverse(uint64_t nid)
{
return _toOrigElem[nid] ;
}
void GetElemList(std::vector<T> &l)
{
l = _toOrigElem ;
}
size_t GetSize()
{
return _toOrigElem.size() ;
}
void Save(FILE *fp)
{
size_t n = GetSize() ;
fwrite(&n, sizeof(n), 1, fp) ;
fwrite(_toOrigElem.data(), sizeof(T), n, fp) ;
}
void Load(FILE *fp)
{
size_t n ;
uint64_t *list ;
fread(&n, sizeof(n), 1, fp) ;
list = new T[n] ;
fread(list, sizeof(T), n, fp) ;
_toOrigElem.clear() ;
_toOrigElem.insert(_toOrigElem.end(), list, list + n) ;
_toNumId.clear() ;
for (size_t i = 0 ; i < n ; ++i)
_toNumId[ _toOrigElem[i] ] = i ;
delete[] list ;
}
} ;
#endif