C
C
CodeInside2016-09-13 20:48:15
C++ / C#
CodeInside, 2016-09-13 20:48:15

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
};

The task is to implement the methods of the AcademyGroup class, whose attribute is a TWO-DIMENSIONAL dynamic array. The teacher said that in this way the data will become more flexible. For example, if there are 1000 students in a group, and you need to add 1 more, then you will have to create a new block of 1000 cells, overwrite data in it, re-declare the old one for 1001 cells and return the data. And if the array is two-dimensional, then you can avoid this turmoil. But I can’t understand how, because I missed this topic (but I know very well about dynamic memory allocation: I went through procedural programming). Can you please explain how this "flexibility" can be used with an example?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
Rsa97, 2016-09-13
@CodeInside

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.

M
Mercury13, 2016-09-13
@Mercury13

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();
}

Removal and other things you will adjust yourself?
And the group will use our list.
#include <string>

class AcademyGroup
{
public:
   std::string name;
   StudentList students;  // при желании можно заинкапсулировать и его.
};

This is before us, however, not a two-dimensional array, as I said. The array, though Student**, is one-dimensional; each array element is a sole proprietorship smart pointer. If we were writing in STL C++11, it would be std::vector<std::unique_ptr<Student>>.
In addition to UUEV, there is also a std::shared_ptr shared smart pointer.
You can make the second option - an array of one-dimensional arrays. If it is full, we start another array. It is written a little more complicated, especially if you do not use STL. On STL - std::deque<Student>.

M
Maxim Moseychuk, 2016-09-13
@fshp

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.

A
abcd0x00, 2016-09-14
@abcd0x00

Here you sketched an example of dividing a large array into subarrays.

The code
#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]$

Regarding the capacity: this part, which is responsible for two-dimensionality, can be redistributed. That is, initially, for example, there were 10 lines of 50 elements, and then at element 501 you simply take these 10 lines, re-select them, preserving what was there, and continue in the same spirit. You should have reselection in the function of adding an element.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question