-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcticketlist.cpp
More file actions
262 lines (225 loc) · 8 KB
/
Copy pathcticketlist.cpp
File metadata and controls
262 lines (225 loc) · 8 KB
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
#include "cticketlist.h"
#include <functional>
// --- Конструктор та Деструктор ---
CTicketList::CTicketList() {
head_ = new CNode();
tail_ = new CNode();
head_->pNext_ = tail_;
tail_->pPrev_ = head_;
count_ = 0;
}
CTicketList::~CTicketList() {
CNode* cur = head_->pNext_;
while (cur != tail_) {
CNode* next = cur->pNext_;
if (this->isOwner && cur->data_ != nullptr) {
delete cur->data_;
}
delete cur;
cur = next;
}
delete head_;
delete tail_;
}
// --- Операції додавання та видалення ---
// Додає новий квиток перед хвостом списку
void CTicketList::addTicket(CSeasonTicket* ticketPtr)
{
CNode* newNode = new CNode(ticketPtr);
CNode* lastReal = tail_->pPrev_;
lastReal->pNext_ = newNode;
newNode->pPrev_ = lastReal;
newNode->pNext_ = tail_;
tail_->pPrev_ = newNode;
count_++;
string tempCity = ticketPtr->getCity();
for (vector<string>::iterator jt = citiesList.begin(); jt != citiesList.end(); jt++) {
if (*jt == tempCity) return;
}
citiesList.push_back(tempCity);
}
// Видаляє квиток за посиланням
int CTicketList::removeTicket(const CSeasonTicket& ticketRef)
{
CNode* current = head_->pNext_;
while (current != tail_)
{
if (*(current->data_) == ticketRef)
{
current->pPrev_->pNext_ = current->pNext_;
current->pNext_->pPrev_ = current->pPrev_;
if (current->data_) {
delete current->data_;
}
delete current;
count_--;
return 1;
}
current = current->pNext_;
}
return 0;
}
// Заповнює вектор citiesList унікальними містами
void CTicketList::initialiseCitiesList()
{
for (CTicketList::Iterator it = head_; it != tail_; it++)
{
string tempCity = (*it)->getCity();
for (vector<string>::iterator jt = citiesList.begin(); jt != citiesList.end(); jt++) {
if (*jt == tempCity) return;
}
citiesList.push_back(tempCity);
}
return;
}
// --- Пошук ---
// Знаходить квиток за ID або кидає виключення
CSeasonTicket* CTicketList::findTicketByID(const int& id) const
{
CNode* current = head_->pNext_;
while (current != tail_) {
if (current->data_->getId() == id)
return current->data_;
current = current->pNext_;
}
throw std::runtime_error("Помилка при спробі знайти елемент за ID");
}
// Повертає новий список квитків для конкретного міста
CTicketList* CTicketList::findTicketsByCity(string city) const
{
CTicketList* resultList = new CTicketList();
resultList->isOwner = false;
for (CTicketList::Iterator it = this->begin(); it != this->end(); it++)
{
if ((**it).getCity() == city) {
resultList->addTicket(*it);
}
}
return resultList;
}
// Повертає новий список квитків для конкретного типу транспорту
CTicketList* CTicketList::findTicketsByTransportType(string transport) const
{
CTicketList* resultList = new CTicketList();
resultList->isOwner = false;
for (CTicketList::Iterator it = this->begin(); it != this->end(); it++)
{
if (transportTypeToString((*it)->getTransportType()) == transport) {
resultList->addTicket(*it);
}
}
return resultList;
}
// Повертає новий список квитків для категорії громадян
CTicketList* CTicketList::findTicketsByCitizenCategory(string category) const
{
CTicketList* resultList = new CTicketList();
resultList->isOwner = false;
for (CTicketList::Iterator it = this->begin(); it != this->end(); it++)
{
if (categoryToString((*it)->getCitizenCategory()) == category) {
resultList->addTicket(*it);
}
}
return resultList;
}
// --- Сортування ---
// Виконує сортування злиттям (Merge Sort) за типом транспорту
void CTicketList::mergeSortTicketsByTransportType()
{
if (count_ < 2 || !head_->pNext_ || head_->pNext_ == tail_) return;
// Від'єднуємо список від head_ та tail_ для сортування
CNode* firstNode = head_->pNext_;
tail_->pPrev_->pNext_ = nullptr;
head_->pNext_ = nullptr;
// Функція злиття двох відсортованих списків
std::function<CNode*(CNode*, CNode*)> merge =
[&](CNode* a, CNode* b) -> CNode* {
if (!a) return b;
if (!b) return a;
int typeA = static_cast<int>(a->data_->getTransportType());
int typeB = static_cast<int>(b->data_->getTransportType());
if (typeA <= typeB) {
a->pNext_ = merge(a->pNext_, b);
return a;
} else {
b->pNext_ = merge(a, b->pNext_);
return b;
}
};
// Рекурсивна функція сортування
std::function<CNode*(CNode*)> sort =
[&](CNode* node) -> CNode* {
if (!node || !node->pNext_) return node;
// Пошук середини (заєць і черепаха)
CNode* slow = node;
CNode* fast = node->pNext_;
while (fast && fast->pNext_) {
slow = slow->pNext_;
fast = fast->pNext_->pNext_;
}
CNode* secondHalf = slow->pNext_;
slow->pNext_ = nullptr;
CNode* left = sort(node);
CNode* right = sort(secondHalf);
return merge(left, right);
};
// Запуск сортування
CNode* newHead = sort(firstNode);
// Відновлення двозв'язної структури та приєднання до head_/tail_
head_->pNext_ = newHead;
newHead->pPrev_ = head_;
CNode* current = newHead;
while (current->pNext_ != nullptr) {
current->pNext_->pPrev_ = current;
current = current->pNext_;
}
current->pNext_ = tail_;
tail_->pPrev_ = current;
}
// --- Робота з файлами ---
// Оператор читання списку з файлу
ifstream& operator>>(ifstream& is, CTicketList& ticketList)
{
int count = 0;
if (!(is >> count) || count == 0) throw std::runtime_error("Помилка: файл порожній");
for (int i = 0; i < count; i++)
{
int type;
is >> type; // 1 - іменний, 0 - звичайний
CSeasonTicket* ticket = nullptr;
if (type == 1) {
ticket = new CNamedTicket();
} else {
ticket = new CSeasonTicket();
}
if (ticket) {
ticket->readFromFile(is);
ticketList.addTicket(ticket);
}
}
return is;
}
// Оператор запису списку у файл
ofstream& operator<<(ofstream& os, const CTicketList& ticketList)
{
if (ticketList.isEmpty()) throw std::runtime_error("Помилка: список порожній");
os << ticketList.count_ << endl;
CTicketList::CNode* current = ticketList.head_->pNext_;
while (current != ticketList.tail_)
{
// Перевірка актуальності квитка
if (current->data_->getDuration() + current->data_->getStartDate() > std::chrono::system_clock::now())
{
if (dynamic_cast<CNamedTicket*>(current->data_) != nullptr) {
os << 1 << " ";
} else {
os << 0 << " ";
}
current->data_->printToFile(os);
os << endl;
current = current->pNext_;
}
}
return os;
}