Advertisement
Gistrec

Simple bd v3

May 11th, 2018
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 6.24 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using std::exception;
  6. using std::string;
  7. using std::vector;
  8. using std::cout;
  9. using std::endl;
  10. using std::cin;
  11.  
  12. // Ошибка: пользователь уже есть в бд
  13. class UserAlreadyExists : public exception {
  14. public:
  15.     int id;
  16.     // Инициализируем переменную user в классе
  17.     UserAlreadyExists(int id) : id(id) {};
  18. };
  19. // Ошибка: пользователь нет в бд
  20. class UserNotFound : public exception {
  21. public:
  22.     int id;
  23.     string name;
  24.     // Дав конструктора - храним либо имя, либо айди
  25.     // Остальные поля - либо -1, либо пустое
  26.     UserNotFound(string const &name) : name(name), id(-1) {};
  27.     UserNotFound(int id) : id(id), name("") {};
  28. };
  29.  
  30. /**
  31.  * Класс пользователя
  32.  * Хрнанит:
  33.  *     Имя пользователя
  34.  *     Id пользователя
  35.  */
  36. class User {
  37. public:
  38.     // Конструктор
  39.     User(int id, string const &name) {
  40.         this->id = id;
  41.         this->name = name;
  42.     }
  43.  
  44.     int getId() const {
  45.         return id;
  46.     }
  47.  
  48.     string getName() const {
  49.         return name;
  50.     }
  51. private:
  52.     int id;
  53.     string name;
  54. };
  55.  
  56. /**
  57.  * Класс базы пользователей
  58.  * Операции:
  59.  *     Добавление нового пользователя
  60.  *     Удаление пользователя (По имени или по Id)
  61.  *     Поиск (По имени или по id)
  62.  */
  63. class DataBase {
  64. public:
  65.     // Если польхователь уже есть в бд - выбрасываем ошибку
  66.     void add(User const &user) {
  67.         // Проверяем на уникальность id
  68.         for (auto it = user_list.begin(); it != user_list.end(); ++it) {
  69.             if (it->getId() == user.getId()) {
  70.                 throw UserAlreadyExists(user.getId());
  71.             }
  72.         }
  73.         user_list.push_back(user);
  74.     }
  75.  
  76.     // Если пользователя нет в бд - выбрасываем ошибку UserNotFound
  77.     void remove(int id) {
  78.         // auto === vector<User>::iterator
  79.         for (auto it = user_list.begin(); it != user_list.end(); ++it) {
  80.             if (it->getId() == id) {
  81.                 user_list.erase(it);
  82.             }
  83.         }
  84.         throw UserNotFound(id);
  85.     }
  86.     void remove(string const &name) {
  87.         for (auto it = user_list.begin(); it != user_list.end(); ++it) {
  88.             if (it->getName() == name) {
  89.                 user_list.erase(it);
  90.             }
  91.         }
  92.         throw UserNotFound(name);
  93.     }
  94.  
  95.     /**
  96.      * Возвращаем результат:
  97.      *     true  - Нашлось
  98.      *     false - Не нашлось
  99.      * Второй параметр - результат.
  100.      * Т.е. он будет содержать найденного пользователя
  101.      */
  102.     bool find(int id, User &result) const {
  103.         for (auto it = user_list.begin(); it != user_list.end(); ++it) {
  104.             if (it->getId() == id) {
  105.                 result = *it;
  106.                 return true;
  107.             }
  108.         }
  109.         return false;
  110.     }
  111.     bool find(string const &name, User &result) const {
  112.         for (auto it = user_list.begin(); it != user_list.end(); ++it) {
  113.             if (it->getName() == name) {
  114.                 result = *it;
  115.                 return true;
  116.             }
  117.         }
  118.         return false;
  119.     }
  120.  
  121.     /**
  122.      * Возвращаем всех пользователей
  123.      */
  124.     vector<User> getAll() const {
  125.         return user_list;
  126.     }
  127.  
  128. private:
  129.     vector<User> user_list;
  130. };
  131.  
  132. int main() {
  133.     setlocale(LC_ALL, "Russian");
  134.  
  135.     DataBase db;
  136.  
  137.     int action = 0;
  138.  
  139.     while (action != 7) {
  140.         cout << "1 - добавить пользователя" << endl;
  141.  
  142.         cout << "2 - найти пользователя по id" << endl;
  143.         cout << "3 - найти пользователя по имени" << endl;
  144.        
  145.         cout << "4 - удалить пользователя по id" << endl;
  146.         cout << "5 - удалить пользователя по имени" << endl;
  147.        
  148.         cout << "6 - вывести всех пользователей" << endl;
  149.         cout << "7 - выйти" << endl;
  150.  
  151.         cin >> action;
  152.         system("cls"); // Отчищаем экран
  153.  
  154.  
  155.         int id;
  156.         string name;
  157.         User user(0, "");
  158.  
  159.         if (action == 1 || action == 2 || action == 4) {
  160.             cout << "Введите id пользователя" << endl;
  161.             cin >> id;
  162.         }
  163.         if (action == 1 || action == 3 || action == 5) {
  164.             cout << "Введите имя пользователя" << endl;
  165.             cin >> name;
  166.         }
  167.  
  168.         try {
  169.             switch (action) {
  170.                 // Добавляем пользователя
  171.                 case 1:
  172.                     db.add(User(id, name));
  173.                     cout << "Пользователь добавлен" << endl;
  174.  
  175.                     break;
  176.                     // Поиск пользователя по id
  177.                 case 2:
  178.                     if (db.find(id, user)) {
  179.                         cout << "Имя пользователя с id == " << id << ": " << user.getName() << endl;
  180.                     } else {
  181.                         cout << "Пользователь с таким id не найден" << endl;
  182.                     }
  183.                     break;
  184.                     // Поиск пользователя по имени
  185.                 case 3:
  186.                     if (db.find(name, user)) {
  187.                         cout << "Id пользователя с именем " << name << ": " << user.getId() << endl;
  188.                     } else {
  189.                         cout << "Пользователь с таким именем не найден" << endl;
  190.                     }
  191.                     break;
  192.                     // Удаление пользователя по id
  193.                 case 4:
  194.                     db.remove(id);
  195.                     cout << "Пользователь удален" << endl;
  196.                     break;
  197.                     // Удаление пользователя по имени
  198.                 case 5:
  199.                     db.remove(name);
  200.                     cout << "Пользователь удален" << endl;
  201.                     break;
  202.                     // Вывод всех пользователей
  203.                 case 6:
  204.                 {
  205.                     cout << "Все пользователи:" << endl;
  206.                     vector<User> users = db.getAll();
  207.  
  208.                     for (auto &user : users) {
  209.                         cout << user.getId() << ":" << user.getName() << endl;
  210.                     }
  211.                 }
  212.             }
  213.         } catch (UserAlreadyExists const &error) {
  214.             cout << "Ошибка: Пользователь с id " << error.id + " уже есть в бд" << endl;
  215.         } catch (UserNotFound const &error) {
  216.             cout << "Ошибка: Пользователь не найден в бд" << endl;
  217.         } catch (...) {
  218.             cout << "Ошибка: Уупс, что-то пошло не так" << endl;
  219.  
  220.         }
  221.     }
  222.     return 0;
  223. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement