Stack.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (C) 2022 The V-Gears Team
  3. *
  4. * This file is part of V-Gears
  5. *
  6. * V-Gears is free software: you can redistribute it and/or modify it under
  7. * terms of the GNU General Public License as published by the Free Software
  8. * Foundation, version 3.0 (GPLv3) of the License.
  9. *
  10. * V-Gears is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. */
  15. #pragma once
  16. #include <deque>
  17. #include <iostream>
  18. /**
  19. * Stack class based on a deque.
  20. */
  21. template<typename T> class Stack {
  22. public:
  23. /**
  24. * Returns whether or not the stack is empty.
  25. *
  26. * @return True if the stack is empty, false if it is not.
  27. */
  28. bool IsEmpty() const{return stack_.empty();}
  29. /**
  30. * Push an item onto the stack.
  31. *
  32. * @param[in] item The item to push.
  33. */
  34. void Push(const T &item){stack_.push_front(item);}
  35. /**
  36. * Pop an item from the stack and return it.
  37. *
  38. * @return The value popped from the stack.
  39. */
  40. T Pop(){
  41. T retval = stack_.front();
  42. stack_.pop_front();
  43. return retval;
  44. }
  45. /**
  46. * Return the topmost item on the stack without removing it.
  47. *
  48. * @return The topmost item on the stack.
  49. */
  50. T &Peek(){return stack_.front();}
  51. /**
  52. * Return the topmost item on the stack without removing it.
  53. *
  54. * @return The topmost item on the stack.
  55. */
  56. const T &Peek() const{return stack_.front();}
  57. /**
  58. * Gets item on a specified stack position without removing it.
  59. *
  60. * @param[in] pos The number of items to skip on the stack.
  61. * @return The desired item from the stack.
  62. */
  63. T &PeekPos(size_t pos){
  64. if (pos >= stack_.size()) std::cerr << "WARNING: Looking outside stack\n";
  65. return stack_.at(pos);
  66. }
  67. /**
  68. * Gets item on a specified stack position without removing it.
  69. *
  70. * @param[in] pos The number of items to skip on the stack.
  71. * @return The desired item from the stack.
  72. */
  73. const T &PeekPos(size_t pos) const{
  74. if (pos >= stack_.size()) std::cerr << "WARNING: Looking outside stack\n";
  75. return stack_.at(pos);
  76. }
  77. private:
  78. /**
  79. * The stack.
  80. */
  81. std::deque<T> stack_;
  82. };