Answer the question
In order to leave comments, you need to log in
How to use the "flexibility" of a two-dimensional array, before a one-dimensional one?
class Student
{
char * name;
char * surname;
int age;
char phone[12];
double average;
public:
// methods
};
class AcademyGroup
{
Student ** pSt;
int count;
public:
// methods
};
Answer the question
In order to leave comments, you need to log in
Here, it's rather not a two-dimensional array, but a one-dimensional array containing pointers to instances of the Student class. Accordingly, when adding a student, not the instances themselves are copied, but only links to them.
So, we have a task: to make a dynamic array of “smart pointers of sole ownership”. A single ownership smart pointer (std::unique_ptr from C++11) is a pointer that owns allocated memory; When the pointer disappears, the memory also disappears.
Since we are just learning, we will not get into self-written C ++ templates, ready-made STL templates (except algorithm and string) and the new C ++ 11 standard, but already implemented in all compilers. This is a pretty severe limitation; If you remove it, you can seriously simplify your life. And for this, we will separate the data structure from vital objects and implement the StudentList object. I write from a sheet, errors are possible.
Yes, and without C ++ 11, it is rather difficult to implement a smart pointer of sole ownership - therefore, we will make the data structure "monolithically", without dividing it into a smart pointer and a dynamic array.
#include <algorithm>
class StudentList
{
public:
StudentList();
~StudentList();
Student& add(); // добавить пустого студента и выдать ссылку на новенького
size_t size() const { return fSize; }
Student& operator[](size_t i) { return *fData[i]; } // можно также наладить проверку диапазона — сделай это сам…
const Student& operator[](size_t i) const { return *fData[i]; }
void clear();
private:
typedef Student* PStudent;
PStudent* fData;
size_t fSize, fCapacity; // реальное кол-во студентов и на сколько студентов у нас заведено памяти.
// Указатели [fSize..fCapacity) резервные, их значение не определено и высвобождать
// их не надо.
enum { BLOCK_SIZE = 16; };
StudentList(const StudentList&) {} // копирование запрещаем, хочешь — реализуй сам и вынеси в public
StudentList& operator=(const StudentList&) { return *this; } // аналогично
};
StudentList::StudentList(); : fData(NULL), fSize(0), fCapacity(0) {}
Student& StudentList::add()
{
// Убедиться, что массива хватает; если нет — расширить
if (fSize >= fCapacity) {
size_t newCapacity = fCapacity + BLOCK_SIZE;
PStudent* newData = new PStudent[newCapacity];
std::copy(fData, fData + fSize, newData);
delete[] fData;
fData = newData;
fCapacity = newCapacity;
}
// Завести нового студента
Student* r = new Student;
fData[fSize++] = r;
return *r;
}
void StudentList::clear()
{
for (size_t i = 0; i < fSize; ++i)
delete fData[i];
delete[] fData;
fData = NULL;
fSize = 0;
fCapacity = 0;
}
StudentList::~StudentList()
{
clear();
}
#include <string>
class AcademyGroup
{
public:
std::string name;
StudentList students; // при желании можно заинкапсулировать и его.
};
std::vector<std::unique_ptr<Student>>
. std::deque<Student>
.
Your data structure does not use a two-dimensional array, but an array of pointers.
You still have to move the array of pointers when adding/removing elements. But it's more efficient than moving an array of objects.
Here you sketched an example of dividing a large array into subarrays.
#include <iostream>
using namespace std;
class Student {
char *name;
char *surname;
int age;
char phone[12];
double average;
public:
Student() {};
~Student() {};
// methods
void set_age(int n) {
age = n;
}
void print_age() {
cout << age << endl;
}
};
class AcademyGroup {
enum { LINES = 10, ONE_LINE = 50 };
Student ***pSt;
int count;
public:
AcademyGroup();
~AcademyGroup();
// methods
void add(Student *p);
void print();
};
AcademyGroup::AcademyGroup()
{
pSt = new Student **[LINES];
for (int i = 0; i < LINES; i++)
pSt[i] = new Student *[ONE_LINE];
count = 0;
}
AcademyGroup::~AcademyGroup()
{
for (int i = 0; i < LINES; i++)
delete [] pSt[i];
delete [] pSt;
count = 0;
}
void AcademyGroup::add(Student *p)
{
pSt[count / ONE_LINE][count % ONE_LINE] = p;
count++;
}
void AcademyGroup::print()
{
for (int i = 0; i < count; i++) {
pSt[i / ONE_LINE][i % ONE_LINE]->print_age();
}
}
int main()
{
AcademyGroup group;
for (int i = 0; i < 200; i++) {
Student *p = new Student;
p->set_age(i + 1);
group.add(p);
}
group.print();
return 0;
}
[[email protected] cpp]$ .iso++ t.cpp -o t
[[email protected] cpp]$ ./t
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
[[email protected] cpp]$
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question