aboutsummaryrefslogtreecommitdiff
path: root/week05/Exercise6.cpp
diff options
context:
space:
mode:
authorSyndamia <kamen@syndamia.com>2024-03-28 09:43:24 +0200
committerSyndamia <kamen@syndamia.com>2024-03-28 09:43:24 +0200
commit70c2c3eab85bee3100ce1c749af03937a6e11e17 (patch)
treede11302f6187f2234485381af99cf131aa9e210b /week05/Exercise6.cpp
parent96fc3d9205fb4fd8ecff960f44ae2e3def929882 (diff)
downloadoop-2023-solutions-70c2c3eab85bee3100ce1c749af03937a6e11e17.tar
oop-2023-solutions-70c2c3eab85bee3100ce1c749af03937a6e11e17.tar.gz
oop-2023-solutions-70c2c3eab85bee3100ce1c749af03937a6e11e17.zip
[w5] Added solutions to exercises 1-7
Diffstat (limited to 'week05/Exercise6.cpp')
-rw-r--r--week05/Exercise6.cpp74
1 files changed, 74 insertions, 0 deletions
diff --git a/week05/Exercise6.cpp b/week05/Exercise6.cpp
new file mode 100644
index 0000000..9f8183e
--- /dev/null
+++ b/week05/Exercise6.cpp
@@ -0,0 +1,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);
+ }
+};