blob: ec2a47acdaf59a5e94b321d86a67f4c045193c5d (
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
75
76
77
78
79
80
81
82
83
84
85
86
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--;
}
|