Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef STACK_CPP11_HPP
- #define STACK_CPP11_HPP
- #include <vector>
- namespace stack {
- template <typename T>
- class Stack {
- private:
- std::vector<T> storage;
- public:
- Stack() : storage() {}
- Stack(const Stack<T> &other) {
- *this = other;
- }
- Stack(Stack<T> &&other) {
- *this = other;
- }
- ~Stack() {
- }
- Stack<T> &operator=(const Stack<T> &rhs) {
- if (this != &rhs)
- storage = rhs.storage;
- return *this;
- }
- Stack<T> &operator=(Stack<T> &&rhs) {
- if (this != &rhs)
- storage = rhs.storage;
- return *this;
- }
- bool top(T &ret) const noexcept {
- if (storage.empty())
- return false;
- ret = storage.back();
- return true;
- }
- void push(T item) noexcept {
- storage.push_back(std::move(item));
- }
- bool pop() noexcept {
- if (storage.empty())
- return false;
- storage.pop_back();
- return true;
- }
- };
- } // namespace stack
- #endif // STACK_CPP11_HPP
- #include <cassert>
- #include <string>
- #include "stack.hpp"
- using namespace stack;
- struct Box {
- std::string label;
- Box(std::string l) : label(l) {}
- friend void swap(Box &lhs, Box &rhs) {
- using std::swap;
- swap(lhs.label, rhs.label);
- }
- Box(const Box &other) {
- label = other.label;
- }
- Box(Box &&other) {
- swap(*this, other);
- }
- ~Box() {
- }
- Box &operator=(Box rhs) {
- swap(*this, rhs);
- return *this;
- }
- };
- int main(void) {
- Stack<int> stack1;
- int ret;
- assert(!stack1.top(ret));
- stack1.push(100);
- assert(stack1.top(ret));
- assert(stack1.pop());
- assert(ret == 100);
- auto stack2 = Stack<Box>();
- Box box("bar");
- assert(!stack2.top(box));
- stack2.push(std::move(Box{"foo"}));
- assert(stack2.top(box));
- assert(stack2.pop());
- assert(box.label == "foo");
- return 0;
- }
Add Comment
Please, Sign In to add comment