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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
#include <iostream>
struct Cell {
private:
int value;
char op;
Cell* left;
Cell* right;
public:
Cell() {
SetValue(0);
}
Cell(int value) {
SetValue(value);
}
Cell(char op, Cell* left, Cell* right) {
SetFormula(op, left, right);
}
int Evaluate() {
switch (op) {
case '+': value = left->GetValue() + right->GetValue(); break;
case '-': value = left->GetValue() - right->GetValue(); break;
case '*': value = left->GetValue() * right->GetValue(); break;
case '/': value = left->GetValue() / right->GetValue(); break;
}
return 0;
}
int GetValue() {
return value;
}
void SetValue(int value) {
op = '\0';
left = right = nullptr;
this->value = value;
}
void SetFormula(char op, Cell* left, Cell* right) {
this-> op = op;
this->left = left;
this->right = right;
Evaluate();
}
};
struct Table {
private:
Cell** cells;
int rows;
int cols;
void evaluateAllCells() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cells[i][j].Evaluate();
}
}
}
public:
Table(int rows, int cols) {
this->rows = rows;
this->cols = cols;
cells = new Cell*[rows];
for (int i = 0; i < rows; i++) {
cells[i] = new Cell[cols];
}
}
~Table() {
for (int i = 0; i < rows; i++) {
delete[] cells[i];
}
delete[] cells;
}
Cell* GetCell(int row, int col) {
return &cells[row][col];
}
void SetCell(int row, int col, Cell cell) {
cells[row][col] = cell;
}
void UpdateCell(int row, int col, int value) {
cells[row][col].SetValue(value);
evaluateAllCells();
}
void UpdateCell(int row, int col, char op, Cell* left, Cell* right) {
cells[row][col].SetFormula(op, left, right);
evaluateAllCells();
}
void Print() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << "|" << cells[i][j].GetValue();
}
std::cout << "|" << std::endl;
}
}
};
int main() {
Table mytable(2, 2);
mytable.SetCell(0, 0, Cell(5));
mytable.SetCell(0, 1, Cell(7));
mytable.SetCell(1, 0, Cell('*', mytable.GetCell(0, 0), mytable.GetCell(0, 1)));
mytable.Print();
return 0;
}
|