diff options
| author | Syndamia <kamen@syndamia.com> | 2024-04-04 20:11:12 +0300 |
|---|---|---|
| committer | Syndamia <kamen@syndamia.com> | 2024-04-04 20:11:12 +0300 |
| commit | a2e284b0056075e2365deaa2455be567c3b3c945 (patch) | |
| tree | 8a842d1f2ffb9f00989b39d2ab7a7ade1a858d81 /week07/Exercise1.cpp | |
| parent | 44d085f265583f0e3cbef294bbe2c8e300aaa452 (diff) | |
| download | oop-2023-solutions-a2e284b0056075e2365deaa2455be567c3b3c945.tar oop-2023-solutions-a2e284b0056075e2365deaa2455be567c3b3c945.tar.gz oop-2023-solutions-a2e284b0056075e2365deaa2455be567c3b3c945.zip | |
[w7] Added exercise descriptions and solutions
Diffstat (limited to 'week07/Exercise1.cpp')
| -rw-r--r-- | week07/Exercise1.cpp | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/week07/Exercise1.cpp b/week07/Exercise1.cpp new file mode 100644 index 0000000..ec2a47a --- /dev/null +++ b/week07/Exercise1.cpp @@ -0,0 +1,87 @@ +#include "Exercise1.h" +#include <cstring> + +/* Private */ + +void Recipe::resize() { + allocated *= 2; + Ingredient* moreIngredients = new Ingredient[allocated]; + for (int i = 0; i < lastIndex; i++) { + moreIngredients[i] = ingredients[i]; + } + delete[] ingredients; + ingredients = moreIngredients; +} + +void Recipe::free() { + delete[] ingredients; +} +void Recipe::copyFrom(const Recipe& other) { + this->lastIndex = other.lastIndex; + this->allocated = other.allocated; + this->ingredients = new Ingredient[allocated]; + for (int i = 0; i < lastIndex; i++) { + this->ingredients[i] = other.ingredients[i]; + } +} + +/* Public */ + +Recipe::Recipe() { + ingredients = nullptr; + lastIndex = allocated = 0; +} +Recipe::~Recipe() { + free(); +} +Recipe::Recipe(const Recipe& other) { + copyFrom(other); +} +Recipe& Recipe::operator=(const Recipe& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; +} +Recipe::Recipe(Recipe&& other) { + this->ingredients = other.ingredients; + this->lastIndex = other.lastIndex; + this->allocated = other.allocated; + + other.ingredients = nullptr; +} +Recipe& Recipe::operator=(Recipe&& other) { + if (this != &other) { + free(); + + this->ingredients = other.ingredients; + this->lastIndex = other.lastIndex; + this->allocated = other.allocated; + + other.ingredients = nullptr; + } + return *this; +} + +void Recipe::AddIngredient(const Ingredient& newIng) { + if (lastIndex == allocated) { + resize(); + } + ingredients[lastIndex++] = newIng; +} +void Recipe::RemoveIngredient(const char* name) { + int index = 0; + while (index < lastIndex && strcmp(ingredients[index].name, name) != 0) { + index++; + } + if (index == lastIndex) { + return; + } + + while (index < lastIndex) { + ingredients[index] = ingredients[index+1]; + index++; + } + lastIndex--; +} |
