Guest User

Untitled

a guest
Dec 16th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. #ifndef STACK_CPP11_HPP
  2. #define STACK_CPP11_HPP
  3.  
  4. #include <vector>
  5.  
  6. namespace stack {
  7.  
  8. template <typename T>
  9. class Stack {
  10. private:
  11. std::vector<T> storage;
  12.  
  13. public:
  14. Stack() : storage() {}
  15.  
  16. Stack(const Stack<T> &other) {
  17. *this = other;
  18. }
  19.  
  20. Stack(Stack<T> &&other) {
  21. *this = other;
  22. }
  23.  
  24. ~Stack() {
  25. }
  26.  
  27. Stack<T> &operator=(const Stack<T> &rhs) {
  28. if (this != &rhs)
  29. storage = rhs.storage;
  30.  
  31. return *this;
  32. }
  33.  
  34. Stack<T> &operator=(Stack<T> &&rhs) {
  35. if (this != &rhs)
  36. storage = rhs.storage;
  37.  
  38. return *this;
  39. }
  40.  
  41. bool top(T &ret) const noexcept {
  42. if (storage.empty())
  43. return false;
  44.  
  45. ret = storage.back();
  46. return true;
  47. }
  48.  
  49. void push(T item) noexcept {
  50. storage.push_back(std::move(item));
  51. }
  52.  
  53. bool pop() noexcept {
  54. if (storage.empty())
  55. return false;
  56.  
  57. storage.pop_back();
  58. return true;
  59. }
  60. };
  61.  
  62. } // namespace stack
  63.  
  64. #endif // STACK_CPP11_HPP
  65.  
  66. #include <cassert>
  67. #include <string>
  68.  
  69. #include "stack.hpp"
  70.  
  71. using namespace stack;
  72.  
  73. struct Box {
  74. std::string label;
  75.  
  76. Box(std::string l) : label(l) {}
  77.  
  78. friend void swap(Box &lhs, Box &rhs) {
  79. using std::swap;
  80. swap(lhs.label, rhs.label);
  81. }
  82.  
  83. Box(const Box &other) {
  84. label = other.label;
  85. }
  86.  
  87. Box(Box &&other) {
  88. swap(*this, other);
  89. }
  90.  
  91. ~Box() {
  92. }
  93.  
  94. Box &operator=(Box rhs) {
  95. swap(*this, rhs);
  96. return *this;
  97. }
  98. };
  99.  
  100. int main(void) {
  101. Stack<int> stack1;
  102.  
  103. int ret;
  104. assert(!stack1.top(ret));
  105.  
  106. stack1.push(100);
  107. assert(stack1.top(ret));
  108. assert(stack1.pop());
  109. assert(ret == 100);
  110.  
  111. auto stack2 = Stack<Box>();
  112.  
  113. Box box("bar");
  114. assert(!stack2.top(box));
  115.  
  116. stack2.push(std::move(Box{"foo"}));
  117. assert(stack2.top(box));
  118. assert(stack2.pop());
  119. assert(box.label == "foo");
  120.  
  121. return 0;
  122. }
Add Comment
Please, Sign In to add comment