Gistrec icon

Simple bd v3

Gistrec | PRO | 05/11/18 09:42:36 PM UTC | 0 ⭐ | 567 👁️ | Never ⏰ | []
C++ |

6.24 KB

|

None

|

0 👍

/

0 👎

#include <iostream>
#include <string>
#include <vector>
 
using std::exception;
using std::string;
using std::vector;
using std::cout;
using std::endl;
using std::cin;
 
// Ошибка: пользователь уже есть в бд
class UserAlreadyExists : public exception {
public:
    int id;
    // Инициализируем переменную user в классе
    UserAlreadyExists(int id) : id(id) {};
};
// Ошибка: пользователь нет в бд
class UserNotFound : public exception {
public:
    int id;
    string name;
    // Дав конструктора - храним либо имя, либо айди
    // Остальные поля - либо -1, либо пустое
    UserNotFound(string const &name) : name(name), id(-1) {};
    UserNotFound(int id) : id(id), name("") {};
};
 
/**
 * Класс пользователя
 * Хрнанит:
 *     Имя пользователя
 *     Id пользователя
 */
class User {
public:
    // Конструктор
    User(int id, string const &name) {
        this->id = id;
        this->name = name;
    }
 
    int getId() const {
        return id;
    }
 
    string getName() const {
        return name;
    }
private:
    int id;
    string name;
};
 
/**
 * Класс базы пользователей
 * Операции:
 *     Добавление нового пользователя
 *     Удаление пользователя (По имени или по Id)
 *     Поиск (По имени или по id)
 */
class DataBase {
public:
    // Если польхователь уже есть в бд - выбрасываем ошибку 
    void add(User const &user) {
        // Проверяем на уникальность id
        for (auto it = user_list.begin(); it != user_list.end(); ++it) {
            if (it->getId() == user.getId()) {
                throw UserAlreadyExists(user.getId());
            }
        }
        user_list.push_back(user);
    }
 
    // Если пользователя нет в бд - выбрасываем ошибку UserNotFound
    void remove(int id) {
        // auto === vector<User>::iterator
        for (auto it = user_list.begin(); it != user_list.end(); ++it) {
            if (it->getId() == id) {
                user_list.erase(it);
            }
        }
        throw UserNotFound(id);
    }
    void remove(string const &name) {
        for (auto it = user_list.begin(); it != user_list.end(); ++it) {
            if (it->getName() == name) {
                user_list.erase(it);
            }
        }
        throw UserNotFound(name);
    }
 
    /**
     * Возвращаем результат:
     *     true  - Нашлось
     *     false - Не нашлось
     * Второй параметр - результат.
     * Т.е. он будет содержать найденного пользователя
     */
    bool find(int id, User &result) const {
        for (auto it = user_list.begin(); it != user_list.end(); ++it) {
            if (it->getId() == id) {
                result = *it;
                return true;
            }
        }
        return false;
    }
    bool find(string const &name, User &result) const {
        for (auto it = user_list.begin(); it != user_list.end(); ++it) {
            if (it->getName() == name) {
                result = *it;
                return true;
            }
        }
        return false;
    }
 
    /**
     * Возвращаем всех пользователей
     */
    vector<User> getAll() const {
        return user_list;
    }
 
private:
    vector<User> user_list;
};
 
int main() {
    setlocale(LC_ALL, "Russian");
 
    DataBase db;
 
    int action = 0;
 
    while (action != 7) {
        cout << "1 - добавить пользователя" << endl;
 
        cout << "2 - найти пользователя по id" << endl;
        cout << "3 - найти пользователя по имени" << endl;
        
        cout << "4 - удалить пользователя по id" << endl;
        cout << "5 - удалить пользователя по имени" << endl;
        
        cout << "6 - вывести всех пользователей" << endl;
        cout << "7 - выйти" << endl;
 
        cin >> action;
        system("cls"); // Отчищаем экран
 
 
        int id;
        string name;
        User user(0, "");
 
        if (action == 1 || action == 2 || action == 4) {
            cout << "Введите id пользователя" << endl;
            cin >> id;
        }
        if (action == 1 || action == 3 || action == 5) {
            cout << "Введите имя пользователя" << endl;
            cin >> name;
        }
 
        try {
            switch (action) {
                // Добавляем пользователя
                case 1:
                    db.add(User(id, name));
                    cout << "Пользователь добавлен" << endl;
 
                    break;
                    // Поиск пользователя по id
                case 2:
                    if (db.find(id, user)) {
                        cout << "Имя пользователя с id == " << id << ": " << user.getName() << endl;
                    } else {
                        cout << "Пользователь с таким id не найден" << endl;
                    }
                    break;
                    // Поиск пользователя по имени
                case 3:
                    if (db.find(name, user)) {
                        cout << "Id пользователя с именем " << name << ": " << user.getId() << endl;
                    } else {
                        cout << "Пользователь с таким именем не найден" << endl;
                    }
                    break;
                    // Удаление пользователя по id
                case 4:
                    db.remove(id);
                    cout << "Пользователь удален" << endl;
                    break;
                    // Удаление пользователя по имени
                case 5:
                    db.remove(name);
                    cout << "Пользователь удален" << endl;
                    break;
                    // Вывод всех пользователей
                case 6:
                {
                    cout << "Все пользователи:" << endl;
                    vector<User> users = db.getAll();
 
                    for (auto &user : users) {
                        cout << user.getId() << ":" << user.getName() << endl;
                    }
                }
            }
        } catch (UserAlreadyExists const &error) {
            cout << "Ошибка: Пользователь с id " << error.id + " уже есть в бд" << endl;
        } catch (UserNotFound const &error) {
            cout << "Ошибка: Пользователь не найден в бд" << endl;
        } catch (...) {
            cout << "Ошибка: Уупс, что-то пошло не так" << endl;
 
        }
    }
    return 0;
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎