Compare commits

...

7 Commits

147
pr6.cpp
View File

@ -1,6 +1,9 @@
#include <iostream>
#include <stdexcept>
#include <functional>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
@ -35,6 +38,8 @@ public:
next = nextElement;
}
virtual ~Element() {}
template<class T1> friend class LinkedList;
template<class T1> friend class DoublyLinkedStack;
template<class T1> friend ostream& operator<<(ostream& s, const Element<T1>& el);
@ -216,7 +221,9 @@ public:
if (this->tail == nullptr)
return nullptr;
DoublyLinkedElement<T>* res = static_cast<DoublyLinkedElement<T>*>(this->tail);
//DoublyLinkedElement<T>* res = static_cast<DoublyLinkedElement<T>*>(this->tail);
// Преобразование указателя на базовый класс в указатель на производный класс
DoublyLinkedElement<T>* res = dynamic_cast<DoublyLinkedElement<T>*>(this->tail);
if (this->head == this->tail) {
this->head = this->tail = nullptr;
@ -401,20 +408,45 @@ public:
// geters
string getName() const { return name; }
double getArea() const { return area; }
long getPopulation() const { return population; }
string getCapital() const { return capital; }
string getLanguage() const { return language; }
};
class StateList {
class StateList : public DoublyLinkedStack<State> {
protected:
SinglyLinkedListQueue<State> stateList;
public:
// Добавление нового государства в начало списка
void addState(const State& state) {
//void addState(const State& state) {
// stateList.push(state);
//}
virtual Element<State>* push(const State& state) override {
stateList.push(state);
return stateList.getHead();
}
friend ostream& operator<<(ostream& os, const StateList& stateList) {
Element<State>* current = stateList.stateList.getHead();
while (current != nullptr) {
os << current->getInfo() << endl;
current = current->getNext();
}
return os;
}
// Удаление государства из начала списка
virtual Element<State>* pop() override {
try {
return new Element<State>(removeState());
}
catch (const logic_error& e) {
cout << e.what() << endl;
return nullptr;
}
}
State removeState() {
Element<State>* element = stateList.pop();
if (element) {
@ -424,7 +456,6 @@ public:
}
throw logic_error("State list is empty");
}
// Поиск государства по названию
State* findStateByName(const string& name) {
Element<State>* current = stateList.getHead();
@ -434,7 +465,6 @@ public:
}
current = current->getNext();
}
/*throw logic_error("State not found");*/
return nullptr;
}
@ -449,8 +479,73 @@ public:
current = current->getNext();
}
}
// Универсальная фильтрация государств по произвольному условию
void printStatesByCondition(function<bool(const State&)> condition) {
Element<State>* current = stateList.getHead();
while (current != nullptr) {
const State& state = current->getInfo();
if (condition(state)) {
cout << state << endl;
}
current = current->getNext();
}
}
// Сохранение списка состояний в файл
void save(const string& filename) const {
ofstream outputFile(filename);
if (!outputFile.is_open()) {
throw runtime_error("Unable to open file for writing");
}
Element<State>* current = stateList.getHead();
while (current != nullptr) {
outputFile << current->getInfo().getName() << ","
<< current->getInfo().getCapital() << ","
<< current->getInfo().getLanguage() << ","
<< current->getInfo().getPopulation() << ","
<< current->getInfo().getArea() << endl;
current = current->getNext();
}
outputFile.close();
}
// Загрузка списка состояний из файла
void load(const string& filename) {
ifstream file(filename);
if (file.is_open()) {
// Очищаем текущий список состояний перед загрузкой новых данных
while (!stateList.isEmpty()) {
stateList.pop();
}
string line;
while (getline(file, line)) {
stringstream ss(line);
string name, capital, language;
long population;
double area;
getline(ss, name, ',');
getline(ss, capital, ',');
getline(ss, language, ',');
ss >> population;
ss.ignore(1); // Ignore the comma
ss >> area;
State state(name, capital, language, population, area);
stateList.push(state);
}
file.close();
}
else {
cout << "Unable to open file for loading" << endl;
}
}
};
int main() {
DoublyLinkedStack<int> stack;
@ -501,25 +596,34 @@ int main() {
}
cout << endl;
//StateList
StateList states;
// Пример использования
states.addState(State("USA", "Washington D.C.", "English", 328000000, 9833510));
states.addState(State("India", "New Delhi", "Hindi", 1380000000, 3287263));
//stateList.addState(usa);
//stateList.addState(india);
StateList* states = new StateList();
//for 6.2
states->push(State("USA", "Washington D.C.", "English", 328000000, 9833510));
states->push(State("India", "New Delhi", "Hindi", 1380000000, 3287263));
// Сохраняем список состояний в файл
states->save("states.txt");
// Загружаем список состояний из файла
StateList loadedStates;
loadedStates.load("states.txt");
cout << "List of states:" << endl;
cout << states.findStateByName("USA") << endl;
//cout << states->findStateByName("USA") << endl;
cout << loadedStates << endl;
//cout << "Removing state:" << endl;
//cout << stateList.removeState() << endl;
cout << "States with area between 9800500 and 9987263:" << endl;
states->printStatesByArea(9800500, 9987263);
cout << "States with area between 2000 and 3000:" << endl;
states.printStatesByArea(2000, 3000);
cout << "States with population greater than 1 billion:" << endl;
states->printStatesByCondition([](const State& state)
{
return state.getPopulation() > 1000000000;
});
State* foundState = states.findStateByName("USA");
State* foundState = states->findStateByName("USA");
if (foundState) {
cout << "Found state: " << *foundState << endl;
}
@ -528,7 +632,7 @@ int main() {
}
try {
State removedState = states.removeState();
State removedState = states->removeState();
cout << "Removed state: " << removedState << endl;
}
catch (const out_of_range& e) {
@ -536,9 +640,10 @@ int main() {
}
cout << "States after removal:" << endl;
states.printStatesByArea(0, 10000);
states->printStatesByArea(0, 10000000);
// Освобождение памяти, выделенной для объекта StateList
delete states;
return 0;
}