-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSparseArray.h
152 lines (126 loc) · 2.27 KB
/
SparseArray.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#pragma once
#include <algorithm>
#include <cassert>
#include <functional>
#include <vector>
namespace spandex
{
template<class T>
class SparseArray
{
public:
int size;
int nnz;
private:
typedef typename std::vector<std::pair<int, T>>::iterator Iterator;
typedef typename std::vector<std::pair<int, T>>::const_iterator ConstIterator;
struct CompareFunc
{
CompareFunc() = default;
bool operator()(const std::pair<int, T>& a, int b) const
{
return a.first < b;
}
bool operator()(int a, const std::pair<int, T>& b) const
{
return a < b.first;
}
};
std::vector<std::pair<int, T>> items;
CompareFunc compareFunc;
public:
SparseArray(int size) : size(size), nnz(0)
{
}
SparseArray(const std::vector<T>& init) : SparseArray((int)init.size())
{
int size = (int)init.size();
for (int i = 0; i < size; i++)
{
Insert(i, init[i]);
}
}
SparseArray(int size, std::initializer_list<std::pair<int, T>> init) : SparseArray(size)
{
for (auto& item : init)
{
Insert(item.first, item.second);
}
}
bool Equals(const SparseArray& that) const
{
if (size != that.size)
{
return false;
}
return items == that.items;
}
Iterator begin()
{
return items.begin();
}
Iterator end()
{
return items.end();
}
ConstIterator begin() const
{
return items.begin();
}
ConstIterator end() const
{
return items.end();
}
void Insert(int index, const T& value)
{
assert(index < size);
auto it = LowerBound(index);
if (it != end() && !compareFunc(index, *it))
{
it->second = value;
}
else
{
items.emplace(it, index, value);
nnz += 1;
}
}
bool Contains(int index)
{
assert(index < size);
return end() != Find(index);
}
void Clear() noexcept
{
nnz = 0;
items.clear();
}
T At(int index)
{
assert(index < size);
auto it = Find(index);
if (end() == it)
{
return T();
}
else
{
return it->second;
}
}
private:
Iterator LowerBound(int index)
{
return std::lower_bound(items.begin(), end(), index, compareFunc);
}
Iterator Find(int index)
{
auto it = LowerBound(index);
if (it != end() && !compareFunc(index, *it))
{
return it;
}
return end();
}
};
}