/*
Вариант № 4
[ChatGPT]
В циклическом списке расположены элементы,
каждый из которых содержит марку автомобиля и его цену.
Составить методы, позволяющие:
а) выбрать автомобиль с наибольшей ценой;
б) выбрать автомобили в порядке увеличения цен.
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;
class Car {
public:
string brand;
int price;
Car (const string& brand, int price)
: brand(brand)
, price(price)
{
}
};
class TDataStructure {
public:
virtual ~TDataStructure() {}
};
class TList : public TDataStructure {
public:
virtual void addCar(const string& brand, int price) = 0;
virtual Car getMostExpensiveCar() const = 0;
virtual vector<Car> getCarsSortedByPrice() const = 0;
virtual ~TList() {}
};
class CyclicList : public TList {
private:
vector<Car*> cars;
public:
void addCar(const string& brand, int price) override;
Car getMostExpensiveCar() const override;
vector<Car> getCarsSortedByPrice() const override;
~CyclicList();
};
// Добавление автомобиля в список
void CyclicList::addCar(const string& brand, int price) {
cars.push_back(new Car(brand, price)); // Выделение памяти для нового объекта Car
}
// Выбор автомобиля с наибольшей ценой
Car CyclicList::getMostExpensiveCar() const {
if (cars.empty()) {
return Car("", -1);
}
Car* mostExpensiveCar = cars[0];
for (Car* car : cars) {
if (car->price > mostExpensiveCar->price) {
mostExpensiveCar = car;
}
}
return *mostExpensiveCar;
}
// Выбор автомобилей в порядке увеличения цен
vector<Car> CyclicList::getCarsSortedByPrice() const {
vector<Car> sortedCars;
for (Car* car : cars) {
sortedCars.push_back(*car); // Добавляем копии автомобилей в новый вектор
}
sort(
sortedCars.begin(),
sortedCars.end(),
[](const Car& a, const Car& b) {
return a.price < b.price;
}
);
return sortedCars;
}
// Деструктор для освобождения памяти
CyclicList::~CyclicList() {
for (Car* car : cars) {
delete car;
}
}
int main() {
CyclicList list;
list.addCar("Toyota", 20000);
list.addCar("BMW", 40000);
list.addCar("Mercedes", 50000);
list.addCar("Ford", 15000);
Car mostExpensive = list.getMostExpensiveCar();
cout << "Самый дорогой автомобиль: " << mostExpensive.brand << " - " << mostExpensive.price << endl;
vector<Car> sortedCars = list.getCarsSortedByPrice();
cout << "Автомобили в порядке возрастания цен:" << endl;
for (const Car& car : sortedCars) {
cout << car.brand << " - " << car.price << endl;
}
return 0;
// Запись результатов в файл
ofstream outputFile("output.txt");
if (outputFile.is_open()) {
outputFile << "Самый дорогой автомобиль: " << mostExpensive.brand << " - " << mostExpensive.price << endl;
outputFile << "Автомобили в порядке возрастания цен:" << endl;
for (const Car& car : sortedCars) {
outputFile << car.brand << " - " << car.price << endl;
}
outputFile.close();
} else {
cerr << "Ошибка открытия файла output.txt" << endl;
}
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: