aboutsummaryrefslogtreecommitdiff
path: root/week05/Exercise6.cpp
blob: 9f8183e642e731df7e8fb198b315ac5a8b135026 (plain) (blame)
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
#include <cstring>

struct PhoneBook {
private:
	char** entries; // Масив от указатели char*
	unsigned allocated;
	unsigned size;

	void resize() {
		allocated *= 2;
		char** moreEntries = new char*[allocated];
		for (int i = 0; i < size; i++) {
			moreEntries[i] = entries[i];
		}
		delete[] entries;
		entries = moreEntries;
	}

	void free() {
		for (int i = 0; i < size; i++) {
			delete[] entries[i];
		}
		delete[] entries;
	}
	void copyFrom(const PhoneBook& other) {
		this->allocated = other.allocated;
		this->size = other.size;
		this->entries = new char*[allocated];
		for (int i = 0; i < size; i++) {
			this->entries[i] = new char[strlen(other.entries[i])+1];
			strcpy(this->entries[i], other.entries[i]);
		}
	}

public:
	PhoneBook() {
		entries = nullptr;
		allocated = size = 0;
	}
	~PhoneBook() {
		free();
	}
	PhoneBook(const PhoneBook& other) {
		copyFrom(other);
	}
	PhoneBook& operator=(const PhoneBook& other) {
		if (this != &other) {
			free();
			copyFrom(other);
		}
		return *this;
	}

	void InsertPerson(const char* entry) {
		if (allocated == size) {
			resize();
		}

		int index = 0;
		while (index < size) {
			if (strcmp(entry, entries[index]) < 0) {
				break;
			}
			index++;
		}

		size++;
		for (int i = size; i > index; i--) {
			entries[i] = entries[i-1];
		}
		entries[index] = new char[strlen(entry)+1];
		strcpy(entries[index], entry);
	}
};