-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathdmap.h
109 lines (98 loc) · 3.53 KB
/
dmap.h
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Copyright (c) 2014 ipkn.
// Licensed under the MIT license.
#pragma once
#include <map>
#include <algorithm>
#include "dvector.h"
namespace dumpable
{
// implemented as sorted array
template <typename K, typename V, typename Compare = std::less<K>>
class dmap
{
public:
dmap() {}
dmap(const std::map<K, V, Compare>& rhs)
: items_(rhs.begin(), rhs.end())
{
}
dmap(const dmap<K, V, Compare>& rhs)
{
items_ = rhs.items_;
}
dmap(dmap<K, V, Compare>&& rhs)
{
items_ = std::move(rhs.items_);
}
void clear()
{
items_.clear();
}
typedef K key_type;
typedef V mapped_type;
typedef std::pair<K, V> value_type;
typedef typename dvector<value_type>::size_type size_type;
size_type size() const { return items_.size(); }
bool empty() const { return items_.empty(); }
typedef Compare key_compare;
class value_compare {
friend class dmap;
protected:
value_compare() {}
public:
bool operator()(const value_type& lhs, const value_type& rhs) const
{
return Compare()(lhs.first, rhs.first);
};
};
typedef value_type& reference;
typedef const value_type& const_reference;
typedef typename dvector<std::pair<K, V>>::iterator iterator;
iterator begin() const { return items_.begin(); }
iterator end() const { return items_.end(); }
value_compare value_comp() const { return value_compare(); }
dmap<K, V, Compare>& operator = (const dmap<K, V, Compare>& rhs)
{
items_ = rhs.items_;
return *this;
}
dmap<K, V, Compare>& operator = (dmap<K, V, Compare>&& rhs) noexcept
{
items_ = std::move(rhs.items_);
return *this;
}
protected:
class find_comp {
friend class dmap;
protected:
find_comp() {}
public:
bool operator()(const value_type& lhs, const value_type& rhs) const
{
return Compare()(lhs.first, rhs.first);
};
bool operator()(const key_type& lhs, const value_type& rhs) const
{
return Compare()(lhs, rhs.first);
};
bool operator()(const value_type& lhs, const key_type& rhs) const
{
return Compare()(lhs.first, rhs);
};
};
public:
iterator find(const K& key) const noexcept
{
iterator it = std::lower_bound(begin(), end(), key, find_comp());
if (it != end() && !key_compare()(key, it->first))
return it;
return end();
}
dumpable::size_t count(const K& key) const noexcept
{
return find(key) == end() ? 0 : 1;
}
private:
dvector<value_type> items_;
};
}