aboutsummaryrefslogtreecommitdiff
path: root/week08/Exercise1.cpp
diff options
context:
space:
mode:
authorSyndamia <kamen@syndamia.com>2024-04-22 15:43:49 +0300
committerSyndamia <kamen@syndamia.com>2024-04-22 15:43:49 +0300
commitf3406754705e508f57768d3d0d8e457ff5b7620c (patch)
tree9f8743208732c21d5dcb51302feb29058edd8e58 /week08/Exercise1.cpp
parentf7ed9a8a6c31b17d54d2f37cc0f12b64f8e4b6d2 (diff)
downloadoop-2023-solutions-f3406754705e508f57768d3d0d8e457ff5b7620c.tar
oop-2023-solutions-f3406754705e508f57768d3d0d8e457ff5b7620c.tar.gz
oop-2023-solutions-f3406754705e508f57768d3d0d8e457ff5b7620c.zip
[w8] Added exercise descriptions and solutions to ex 1-7
Diffstat (limited to 'week08/Exercise1.cpp')
-rw-r--r--week08/Exercise1.cpp80
1 files changed, 80 insertions, 0 deletions
diff --git a/week08/Exercise1.cpp b/week08/Exercise1.cpp
new file mode 100644
index 0000000..0686a2c
--- /dev/null
+++ b/week08/Exercise1.cpp
@@ -0,0 +1,80 @@
+#include "Exercise1.h"
+#include <cstring>
+
+void StreetList::free() {
+ for (int i = 0; i < lastUnused; i++) {
+ delete[] streetNames[i];
+ }
+ delete[] streetNames;
+}
+
+void StreetList::copyFrom(const StreetList& other) {
+ this->lastUnused = other.lastUnused;
+ this->allocated = other.allocated;
+
+ this->streetNames = new char*[allocated];
+ for (int i = 0; i < lastUnused; i++) {
+ this->streetNames[i] = new char[strlen(other.streetNames[i]) + 1];
+ strcpy(this->streetNames[i], other.streetNames[i]);
+ }
+}
+
+void StreetList::resize() {
+ allocated *= 2;
+ char** biggerList = new char*[allocated];
+ for (int i = 0; i < lastUnused; i++) {
+ // Понеже са указатели в динамичната памет, можем да си спестим new char[] и strcpy
+ biggerList[i] = streetNames[i];
+ }
+ delete[] streetNames;
+ streetNames = biggerList;
+}
+
+StreetList::StreetList() {
+ streetNames = nullptr;
+ lastUnused = allocated = 0;
+}
+
+StreetList::~StreetList() {
+ free();
+}
+
+StreetList::StreetList(const StreetList& other) {
+ copyFrom(other);
+}
+
+StreetList& StreetList::operator=(const StreetList& other) {
+ if (this != &other) {
+ free();
+ copyFrom(other);
+ }
+ return *this;
+}
+
+StreetList::StreetList(StreetList&& other) {
+ this->streetNames = other.streetNames;
+ other.streetNames = nullptr;
+ this->lastUnused = other.lastUnused;
+ this->allocated = other.allocated;
+}
+
+StreetList& StreetList::operator=(StreetList&& other) {
+ if (this != &other) {
+ free();
+
+ this->streetNames = other.streetNames;
+ other.streetNames = nullptr;
+ this->lastUnused = other.lastUnused;
+ this->allocated = other.allocated;
+ }
+ return *this;
+}
+
+void StreetList::Add(const char* newString) {
+ if (lastUnused == allocated) {
+ resize();
+ }
+ streetNames[lastUnused] = new char[strlen(newString) + 1];
+ strcpy(streetNames[lastUnused], newString);
+ lastUnused++;
+}