assoctab.h
1.33 KB
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
#ifndef __ASSOCTAB_H__
#define __ASSOCTAB_H__
#include "vector.h"
#include <string.h>
class assocTab
{
private:
struct node
{
node *next;
char *key;
int val;
node (const char *k):next (NULL)
{
key = new char[strlen (k) + 1];
strcpy (key, k);
};
~node ()
{
delete[]key;
}
node (const node & s):next (NULL)
{
if (s.key == NULL)
key = NULL;
else
{
key = new char[strlen (s.key) + 1];
strcpy (key, s.key);
}
val=s.val;
};
private: //assignment not allowed
node & operator= (const node &);
};
node *head;
void insert (const char *key, int value);
void clear ();
node *find (const char *key) const;
void swap (assocTab & l);
public:
assocTab ();
assocTab (const assocTab & l);
assocTab & operator= (const assocTab & l);
~assocTab ();
int &operator[] (const char *);
};
class hashAssocTab
{
vector<assocTab> v;
int chains;
public:
hashAssocTab(unsigned int c): v(c),chains(c){};
unsigned int hash(const char* s)
{
unsigned sum=0;
while(*s)
{
sum=65599u*sum+(unsigned char)(*s);
s++;
}
return sum % chains;
}
int& operator[] (const char *s)
{
return (v[hash(s)])[s];
}
// default constructor, destructor and assignment operator not necessary
};
#endif /* __ASSOCTAB_H__ */