Skip to content

Commit 57f3f73

Browse files
committed
Chapter 3: Use custom class
instead of `std::deque<std::string>` for `Prefix`
1 parent e84ba3d commit 57f3f73

File tree

1 file changed

+67
-22
lines changed

1 file changed

+67
-22
lines changed

chapter-3/3.6-c++/structs.cpp

Lines changed: 67 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,13 @@
33
#include <map>
44
#include <vector>
55

6+
enum
7+
{
8+
NHASH = 4098,
9+
};
10+
11+
std::hash<std::string> hasher;
12+
613
class Suffixes
714
{
815
private:
@@ -40,35 +47,74 @@ class Suffixes
4047
}
4148
};
4249

43-
typedef std::deque<std::string> Prefix;
44-
std::hash<std::string> hasher;
45-
46-
// todo: make instance methods of Prefix
47-
int hash_prefix(Prefix p)
50+
class Prefix
4851
{
49-
unsigned int h = 0;
52+
public:
53+
std::string values[2];
54+
int _size;
5055

51-
for (int i = 0; i < p.size(); i++)
56+
int size()
5257
{
53-
h += hasher(p.at(i));
58+
return _size;
59+
}
60+
std::string at(int index)
61+
{
62+
return values[index];
63+
}
64+
void push_back(std::string val)
65+
{
66+
values[_size++] = val;
67+
}
68+
void pop_front()
69+
{
70+
if (_size == 2)
71+
{
72+
values[0] = values[1];
73+
values[1] = std::string();
74+
}
75+
else if (_size == 1)
76+
{
77+
values[0] = std::string();
78+
}
79+
else if (_size == 0)
80+
{
81+
return;
82+
}
83+
_size--;
5484
}
5585

56-
return h % 4098;
57-
}
86+
int hash()
87+
{
88+
unsigned int h = 0;
5889

59-
bool prefix_equals(Prefix first, Prefix second)
60-
{
61-
if (first.size() != second.size())
62-
return false;
90+
for (int i = 0; i < size(); i++)
91+
{
92+
h += hasher(at(i));
93+
}
6394

64-
for (int i = 0; i < first.size(); i++)
95+
return h % NHASH;
96+
}
97+
98+
bool operator==(Prefix other)
6599
{
66-
if (first.at(i).compare(second.at(i)) != 0)
100+
if (size() != other.size())
67101
return false;
102+
103+
for (int i = 0; i < size(); i++)
104+
if (at(i).compare(other.at(i)) != 0)
105+
return false;
106+
107+
return true;
68108
}
69109

70-
return true;
71-
}
110+
Prefix()
111+
{
112+
_size = 0;
113+
values[0] = std::string();
114+
values[1] = std::string();
115+
}
116+
};
117+
72118
class StateMap
73119
{
74120
private:
@@ -81,15 +127,14 @@ class StateMap
81127
};
82128

83129
public:
84-
std::map<Prefix, Suffixes> _map;
85-
StateMapEntry *entries[4098];
130+
StateMapEntry *entries[NHASH];
86131

87132
Suffixes *operator[](Prefix p)
88133
{
89-
int hash = hash_prefix(p);
134+
int hash = p.hash();
90135
for (StateMapEntry *e = entries[hash]; e != NULL; e = e->next)
91136
{
92-
if (prefix_equals(p, *e->prefix))
137+
if (p == *e->prefix)
93138
{
94139
return e->suffixes;
95140
}

0 commit comments

Comments
 (0)