Advertisement
AndryS1

Untitled

Feb 19th, 2023
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <functional>
  5.  
  6. class ConsoleMenu {
  7.   private:
  8.     struct MenuItem {
  9.       std::string label;
  10.       std::function<void()> action;
  11.       ConsoleMenu subMenu;
  12.     };
  13.  
  14.     std::vector<MenuItem> items;
  15.  
  16.   public:
  17.     void addItem(const std::string& label, const std::function<void()>& action) {
  18.       items.push_back({ label, action, {} });
  19.     }
  20.  
  21.     ConsoleMenu& addSubMenu(const std::string& label) {
  22.       items.push_back({ label, {}, {} });
  23.       return items.back().subMenu;
  24.     }
  25.  
  26.     void show() const {
  27.       while (true) {
  28.         // Выводим список опций
  29.         std::cout << "Выберите опцию:" << std::endl;
  30.         for (int i = 0; i < items.size(); i++) {
  31.           std::cout << i + 1 << ") " << items[i].label << std::endl;
  32.         }
  33.  
  34.         // Считываем номер выбранной опции
  35.         int choice;
  36.         std::cin >> choice;
  37.  
  38.         // Выполняем действие, соответствующее выбранной опции
  39.         if (choice >= 1 && choice <= items.size()) {
  40.           const auto& selectedItem = items[choice - 1];
  41.           if (selectedItem.action) {
  42.             // Это обычная опция
  43.             selectedItem.action();
  44.           } else {
  45.             // Это подменю
  46.             selectedItem.subMenu.show();
  47.           }
  48.         } else {
  49.           std::cout << "Неверный выбор" << std::endl;
  50.         }
  51.       }
  52.     }
  53. };
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement