@KseniaKlim

Как реализовать добавление и удаление элементов вектора в классe?

Необходимо реализовать добавление, удаление и вывод элементов вектора в классе Catalog, а также чтобы при изменениях элементов, выводились новые данные. Не понимаю как это сделать(
#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Catalog
{
private:
    vector<Item> catalog;

public:
    void addItem(const Item& item) {
        catalog.push_back(item);
    }

    void removeItem(string title) {
        for (auto it = catalog.begin(); it != catalog.end(); ++it) {
            if (it->title == title) {
                catalog.erase(it);
                return;
            }
        }
    }

    void printCatalog() {
        for (auto& item : catalog) {
            item.printInfo();
        }
    }
};

struct User
{
    string name;
    string address;
    string number;
    string mail;

    User(string p_name, string p_address, string p_number, string p_mail) : name(p_name), address(p_address), number(p_number), mail(p_mail) {}

    void printInfo() {
        cout << "Имя: " << name << ", Адрес: " << address << ", Номер телефона: " << number << ", Почта: " << mail << endl;
    }
};

class Item 
{
public:
    string title;
    double price;
    int number;

    Item(string p_title, double p_price, int p_number) : title(p_title), price(p_price), number(p_number) {}

    void printInfo() {
        cout << "Название: " << title << ", Цена: " << price << ", Количество на складе: " << number << endl;
    }

    void updateInfo(double p_price) {
        price = p_price;

    }

    void updateInfo(int p_number) {
        number = p_number;
    }
    
    Item& operator=(const Item& other)
    {
        this->title = other.title;
        this->price = other.price;
        this->number = other.number;
        return *this;
    }

    
    bool operator==(const Item& other) const
    {
        return (this->title == other.title && this->price == other.price && this->number == other.number);
    }
};

class Clothes : public Item {
public:
    string size;
    string color;

    Clothes(string p_title, double p_price, int p_number, string p_size, string p_color) : Item(p_title, p_price, p_number), size(p_size), color(p_color) {}

    void changeSize(string p_size) {
        size = p_size;
    }

    void changeColor(string p_color) {
        color = p_color;
    }

    void printInfo() {
        cout << "Название: " << title << ", Цена: " << price << ", Количество на складе: " << number << ", Размер: " << size << ", Цвет: " << color << endl;
    }
};

class Shoes : public Item {
public:
    string size;
    string type;

    Shoes(string p_title, double p_price, int p_number, string p_size, string p_type) : Item(p_title, p_price, p_number), size(p_size), type(p_type) {}

    void changeSize(string p_size) {
        size = p_size;
    }

    void changeType(string p_type) {
        type = p_type;
    }

    void printInfo() {
        cout << "Название: " << title << ", Цена: " << price << ", Количество на складе: " << number << ", Размер: " << size << ", Тип: " << type << endl;
    }
};
int main() 
{
    setlocale(LC_ALL, "Russian");
    Catalog catalog;
    User user1("Лиза", "ул. Анны Ахматовой д.22", "79773079796", "paputsya@mail.ru");
    Item item1("Сумка", 40.0, 10);
    Item item2("Ремень", 20.0, 15);
    Item item3 = item2;
    Clothes clothes1("Футболка", 15.0, 19, "M", "Синяя");
    Clothes clothes2("Лонгслив", 25.0, 10, "S", "Белый");
    Shoes shoes1("Кроссовки Nike", 50.0, 15, "38", "Кроссовки");
    Shoes shoes2("Кеды Converse", 43.0, 13, "36", "Кеды");

    catalog.addItem(item1);
    catalog.addItem(item2);
    catalog.addItem(item3);
    catalog.addItem(clothes1);
    catalog.addItem(clothes2);
    catalog.addItem(shoes1);
    catalog.addItem(shoes2);


    user1.printInfo();
    catalog.printCatalog();

    clothes1.changeColor("black");
    clothes1.updateInfo(55);

    catalog.printCatalog();


	int n = 1;
	cout << "1. Посмотпеть данные пользователя" << endl;
	cout << "2. Посмотреть каталог" << endl;
	cout << "3. Изменить цену товара или его кол-во на скаладе" << endl;
	cout << "4. Изменить данные о товаре" << endl;
	cout << "5. Добавить товар" << endl;
	cout << "6. Удалить товар" << endl;
	cout << "0. Выход" << endl;
	cout << endl;
	cout << "Выберите действие: ";
	cin >> n;
	try
	{
		if (n < 0 || n > 6)
		{
			throw "Такого действия не существует.";
		}
	}
	catch (const char* message)
	{
		cerr << "Ошибка: " << message << endl;
		cout << "Выберите действие (число от 0 до 4): ";
		cin >> n;
	}
	while (n != 0)
	{
		if (n == 1)
		{
		}
		if (n == 2)
		{
		}
		if (n == 3)
		{
		}
		if (n == 4)
		{
		}
        if (n == 5)
        {
        }
        if (n == 6)
        {
        }
		if (n == 0) break;
	}
    return 0;
}
  • Вопрос задан
  • 54 просмотра
Пригласить эксперта
Ответы на вопрос 1
perfect_genius
@perfect_genius
Неостановимый генератор идей по улучшению мира
Вместо полотна кода, который мало кто будет читать, лучше опиши как мыслишь при решении задачи и в каком месте результат не устраивает.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы