menu.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include <algorithm>
  2. #include <iostream>
  3. #include "menu.h"
  4. const char CMenu::STR_DEFAULT_TITLE[] = "Please, choose:";
  5. const char CMenu::STR_DEFAULT_DIVIDER[] = " - ";
  6. const char CMenu::STR_DEFAULT_PREFIX[] = "";
  7. bool CMenu::addItem(const menuMapValue &_item)
  8. {
  9. if (m_MenuMap.find(_item.first) != m_MenuMap.end())
  10. {
  11. return false;
  12. }
  13. m_MenuMap.insert(_item);
  14. return true;
  15. }
  16. bool CMenu::addItem(const menuMapKey _key, const menuMapItem &_item)
  17. {
  18. return addItem(std::make_pair(_key, _item));
  19. }
  20. bool CMenu::addItem(const menuMapKey _key, const std::string _title, const menuFuncPtr _item)
  21. {
  22. return addItem(_key, MenuItem(_title, _item));
  23. }
  24. void CMenu::draw() const
  25. {
  26. std::cout << std::endl << m_Title << std::endl;
  27. // for_each with lambda-function
  28. // need capture (this) to access class members (m_Prefix, m_Divider)
  29. for_each(m_MenuMap.cbegin(), m_MenuMap.cend(), [this](const menuMapValue& _item)
  30. {
  31. std::cout << m_Prefix <<_item.first << m_Divider << _item.second.title << std::endl;
  32. }
  33. );
  34. std::cout << std::endl;
  35. }
  36. int CMenu::selectItem() const
  37. {
  38. char cKey;
  39. menuMapCIt it;
  40. do
  41. {
  42. std::cin >> cKey;
  43. it = m_MenuMap.find(cKey);
  44. }
  45. while (it == m_MenuMap.cend());
  46. if (it->second.item != nullptr)
  47. {
  48. return (*it->second.item)();
  49. }
  50. return -1;
  51. }