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

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 308880c was 3fb7f5e, checked in by Aaron Moss <a3moss@…>, 7 years ago

Update benchmarks, cleanup edits to the evaluation section

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