Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef TEST_STACK_H
- #define TEST_STACK_H
- #include <stdexcept>
- template <class T>
- class stack {
- struct node {
- T data;
- node* previous;
- node(T data, node *previous) : data(data), previous(previous) {}
- };
- node* head = nullptr;
- int size = 0;
- int max = -1; // -1 so isFull() == false when default constructor used
- public:
- stack() = default;
- stack(int max) {
- if (max <= 0) throw std::out_of_range("stack size must be > 0");
- this->max = max;
- }
- // copy constructor
- stack(stack const& rhs) :
- head(copyList(rhs.head)),
- size(rhs.size),
- max(rhs.size) {}
- // assignment operator
- stack& operator = (stack const& rhs)
- {
- stack tmp(rhs);
- swap(tmp);
- return *this;
- }
- ~stack() {
- node* n = head;
- while (n != nullptr) {
- node* previous = n->previous;
- delete n;
- n = previous;
- }
- }
- void push(const T &object) {
- if (isFull()) throw std::overflow_error("cannot push to a full stack");
- head = new node(object, head);
- ++size;
- }
- const void pop() {
- if (head == nullptr) throw std::underflow_error("cannot get item from empty stack");
- node* old = head;
- head = head->previous;
- --size;
- delete old;
- }
- T peek() {
- if (head == nullptr) throw std::underflow_error("cannot get item from empty stack");
- return head->data;
- }
- int getSize() {
- return size;
- }
- bool isFull() {
- return size == max;
- }
- bool isEmpty() {
- return head == nullptr;
- }
- void swap(stack& other) noexcept
- {
- using std::swap;
- swap(head, other.head);
- swap(size, other.size);
- swap(max, other.max);
- }
- private:
- node* copyList(node* l)
- {
- if (l == nullptr) {
- return nullptr;
- }
- return new node{l->data, copyList(l->previous)};
- }
- };
- #endif
- #include <stdexcept>
- stack(int max) {
- void foo(stack<int> s);
- void bar() {
- foo(42); // compiles and calls foo with stack<int>(42)
- }
- int max = -1; // -1 so isFull() == false when default constructor used
- if (max <= 0) throw std::out_of_range("stack size must be > 0");
- this->max = max;
- max_ = max;
- stack(stack const& rhs) :
- head(copyList(rhs.head)),
- size(rhs.size),
- max(rhs.size) {}
- stack& operator = (stack const& rhs)
- {
- stack tmp(rhs);
- swap(tmp);
- return *this;
- }
- stack& operator=(stack const& rhs)
- {
- stack(rhs).swap(*this);
- return *this;
- }
- const void pop() {
- T peek() {
- T peek() const {
- if (head == nullptr) throw std::underflow_error("cannot get item from empty stack");
- return std::as_const(head->data);
- }
- void swap(stack& other) noexcept
- friend void swap(stack& a, stack& b) noexcept {
- a.swap(b);
- }
- using std::swap;
- swap(redstack, bluestack);
- node* copyList(node* l)
- static node *copyList(const node *l)
Add Comment
Please, Sign In to add comment