Compare commits

...
7 Commits
+126 -21
View File
@@ -1,6 +1,9 @@
#include <iostream> #include <iostream>
#include <stdexcept> #include <stdexcept>
#include <functional> #include <functional>
#include <fstream>
#include <sstream>
#include <string>
using namespace std; using namespace std;
@@ -35,6 +38,8 @@ public:
next = nextElement; next = nextElement;
} }
virtual ~Element() {}
template<class T1> friend class LinkedList; template<class T1> friend class LinkedList;
template<class T1> friend class DoublyLinkedStack; template<class T1> friend class DoublyLinkedStack;
template<class T1> friend ostream& operator<<(ostream& s, const Element<T1>& el); template<class T1> friend ostream& operator<<(ostream& s, const Element<T1>& el);
@@ -216,7 +221,9 @@ public:
if (this->tail == nullptr) if (this->tail == nullptr)
return 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) { if (this->head == this->tail) {
this->head = this->tail = nullptr; this->head = this->tail = nullptr;
@@ -401,20 +408,45 @@ public:
// geters // geters
string getName() const { return name; } string getName() const { return name; }
double getArea() const { return area; } 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: protected:
SinglyLinkedListQueue<State> stateList; SinglyLinkedListQueue<State> stateList;
public: 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); 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() { State removeState() {
Element<State>* element = stateList.pop(); Element<State>* element = stateList.pop();
if (element) { if (element) {
@@ -424,7 +456,6 @@ public:
} }
throw logic_error("State list is empty"); throw logic_error("State list is empty");
} }
// Поиск государства по названию // Поиск государства по названию
State* findStateByName(const string& name) { State* findStateByName(const string& name) {
Element<State>* current = stateList.getHead(); Element<State>* current = stateList.getHead();
@@ -434,7 +465,6 @@ public:
} }
current = current->getNext(); current = current->getNext();
} }
/*throw logic_error("State not found");*/
return nullptr; return nullptr;
} }
@@ -449,8 +479,73 @@ public:
current = current->getNext(); 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() { int main() {
DoublyLinkedStack<int> stack; DoublyLinkedStack<int> stack;
@@ -501,25 +596,34 @@ int main() {
} }
cout << endl; cout << endl;
//StateList
StateList states;
// Пример использования StateList* states = new StateList();
states.addState(State("USA", "Washington D.C.", "English", 328000000, 9833510));
states.addState(State("India", "New Delhi", "Hindi", 1380000000, 3287263)); //for 6.2
//stateList.addState(usa); states->push(State("USA", "Washington D.C.", "English", 328000000, 9833510));
//stateList.addState(india); 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 << "List of states:" << endl;
cout << states.findStateByName("USA") << endl; //cout << states->findStateByName("USA") << endl;
cout << loadedStates << endl;
//cout << "Removing state:" << endl; cout << "States with area between 9800500 and 9987263:" << endl;
//cout << stateList.removeState() << endl; states->printStatesByArea(9800500, 9987263);
cout << "States with area between 2000 and 3000:" << endl; cout << "States with population greater than 1 billion:" << endl;
states.printStatesByArea(2000, 3000); states->printStatesByCondition([](const State& state)
{
return state.getPopulation() > 1000000000;
});
State* foundState = states.findStateByName("USA"); State* foundState = states->findStateByName("USA");
if (foundState) { if (foundState) {
cout << "Found state: " << *foundState << endl; cout << "Found state: " << *foundState << endl;
} }
@@ -528,7 +632,7 @@ int main() {
} }
try { try {
State removedState = states.removeState(); State removedState = states->removeState();
cout << "Removed state: " << removedState << endl; cout << "Removed state: " << removedState << endl;
} }
catch (const out_of_range& e) { catch (const out_of_range& e) {
@@ -536,9 +640,10 @@ int main() {
} }
cout << "States after removal:" << endl; cout << "States after removal:" << endl;
states.printStatesByArea(0, 10000); states->printStatesByArea(0, 10000000);
// Освобождение памяти, выделенной для объекта StateList
delete states;
return 0; return 0;
} }