diff options
| author | Syndamia <kamen@syndamia.com> | 2024-03-28 09:43:24 +0200 |
|---|---|---|
| committer | Syndamia <kamen@syndamia.com> | 2024-03-28 09:43:24 +0200 |
| commit | 70c2c3eab85bee3100ce1c749af03937a6e11e17 (patch) | |
| tree | de11302f6187f2234485381af99cf131aa9e210b /week05/Exercise4.cpp | |
| parent | 96fc3d9205fb4fd8ecff960f44ae2e3def929882 (diff) | |
| download | oop-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/Exercise4.cpp')
| -rw-r--r-- | week05/Exercise4.cpp | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/week05/Exercise4.cpp b/week05/Exercise4.cpp new file mode 100644 index 0000000..6fbb5f6 --- /dev/null +++ b/week05/Exercise4.cpp @@ -0,0 +1,67 @@ +struct Receipt { +private: + float* prices; + unsigned allocated; + unsigned size; + + void resize() { + allocated *= 2; + float* morePrices = new float[allocated]; + for (int i = 0; i < size; i++) { + morePrices[i] = prices[i]; + } + delete[] prices; + prices = morePrices; + } + + void free() { + delete[] prices; + } + void copyFrom(const Receipt& other) { + this->allocated = other.allocated; + this->size = other.size; + + this->prices = new float[allocated]; + for (int i = 0; i < size; i++) { + this->prices[i] = other.prices[i]; + } + } + +public: + Receipt() { + allocated = 2; + size = 0; + prices = new float[allocated]; + } + ~Receipt() { + free(); + } + Receipt(const Receipt& other) { + copyFrom(other); + } + Receipt& operator=(const Receipt& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; + } + + void AddItemPrice(float price) { + if (price < 0.0) return; + + if (this->allocated == this->size) { + resize(); + } + this->prices[size++] = price; + } + + void RemoveItemPrice(unsigned index) { + if (index >= size) return; + + size--; + for (int i = index; i < size; i++) { + this->prices[i] = this->prices[i+1]; + } + } +}; |
