source: doc/generic_types/evaluation/cpp-stack.hpp @ a381b46

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since a381b46 was a381b46, checked in by Aaron Moss <a3moss@…>, 7 years ago

Minor cleanup, also filled in benchmark source appendix

  • Property mode set to 100644
File size: 1.2 KB
RevLine 
[d919f47]1#pragma once
[309be81]2#include <utility>
3
4template<typename T> class stack {
5        struct node {
6                T value;
7                node* next;
8
[122aecd]9                node( T& v ) : value(v), next(nullptr) {}
[309be81]10                node( T&& v, node* n ) : value(std::move(v)), next(n) {}
11        };
12        node* head;
13
[122aecd]14        void copy(const stack<T>& o) {
15                node** crnt = &head;
16                node* next = o.head;
17                while ( next ) {
[3fb7f5e]18                        *crnt = new node{ next->value }; /***/
[122aecd]19                        crnt = &(*crnt)->next;
20                        next = next->next;
21                }
22                *crnt = nullptr;
23        }
24public:
25        void clear() {
[309be81]26                node* next = head;
27                while ( next ) {
28                        node* crnt = next;
29                        next = crnt->next;
30                        delete crnt;
31                }
[0d10090]32                head = nullptr;
[309be81]33        }
34
[122aecd]35        stack() : head(nullptr) {}
36        stack(const stack<T>& o) { copy(o); }
37        stack(stack<T>&& o) : head(o.head) { o.head = nullptr; }
38        ~stack() { clear(); }
39
40        stack& operator= (const stack<T>& o) {
41                if ( this == &o ) return *this;
42                clear();
43                copy(o);
[b276be5]44                return *this;
[122aecd]45        }
46
47        stack& operator= (stack<T>&& o) {
48                if ( this == &o ) return *this;
49                head = o.head;
50                o.head = nullptr;
51                return *this;
52        }
53
[a381b46]54        bool empty() const { return head == nullptr; }
[309be81]55
[a381b46]56        void push(T&& value) { head = new node{ std::move(value), head };  /***/ }
[309be81]57
58        T pop() {
59                node* n = head;
60                head = n->next;
61                T x = std::move(n->value);
62                delete n;
63                return x;
64        }
65};
Note: See TracBrowser for help on using the repository browser.