assoctab.cpp
1.31 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
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
using namespace std;
#include "assoctab.h"
assocTab::assocTab()
{
head = NULL;
}
void assocTab::clear()
{
while (head) {
node* t = head->next;
delete head;
head = t;
};
}
assocTab::~assocTab()
{
clear();
}
void assocTab::insert(const char* key, int value)
{
node* newnode = new node(key);
newnode->next = head;
head = newnode;
head->val = value;
}
void assocTab::swap(assocTab& l)
{
node* t = head;
head = l.head;
l.head = t;
}
assocTab::assocTab(const assocTab& l)
{
node *src, **dst;
head = NULL;
src = l.head;
dst = &head;
try {
while (src) {
*dst = new node(*src);
src = src->next;
dst = &((*dst)->next);
}
}
catch (...) {
clear();
throw;
};
}
assocTab& assocTab::operator=(const assocTab& l)
{
if (&l == this)
return *this;
assocTab t(l);
swap(t);
return *this;
}
assocTab::node* assocTab::find(const char* key) const
{
node* c = head;
while (c) {
if (!strcmp(c->key, key))
return c;
c = c->next;
};
return NULL;
}
int& assocTab::operator[](const char* key)
{
node* c = find(key);
if (!c) {
insert(key, 0);
c = head;
};
return c->val;
}