collection2  v0.6.0
Loading...
Searching...
No Matches
stack.hpp
1//
2// スタック
3//
4
5#ifndef _COLLECTION2_STACK_H_
6#define _COLLECTION2_STACK_H_
7
8#include <stddef.h>
9
10#include "common.hpp"
11
12namespace collection2 {
13
20template <typename Element, typename Size = size_t>
21class Stack {
22 private:
26 Element* const internalData;
27
31 Size internalDataSize;
32
36 Size sp = 0;
37
38 public:
45 Stack(Element* const data, const Size& dataSize);
46
47 Stack(const Stack&) = delete;
48 Stack& operator=(const Stack&) = delete;
49
50 ~Stack() = default;
51
58 OperationResult push(const Element& data);
59
66 OperationResult pop(Element* const data);
67
73 Size capacity() const {
74 return internalDataSize;
75 }
76
82 Size amount() const {
83 return sp;
84 }
85
91 bool hasSpace() const {
92 return sp < internalDataSize;
93 }
94
100 bool isEmpty() const {
101 return sp == 0;
102 }
103};
104
105template <typename Element, typename Size>
106Stack<Element, Size>::Stack(Element* const data, const Size& dataSize) : internalData(data), internalDataSize(dataSize){};
107
108template <typename Element, typename Size>
110 // スタックがいっぱいなら戻る
111 if (!hasSpace()) {
112 return OperationResult::Overflow;
113 }
114
115 // spの位置にデータを書き込んで進める
116 *(internalData + sp) = data;
117 sp++;
118
119 return OperationResult::Success;
120}
121
122template <typename Element, typename Size>
124 // スタックが空なら戻る
125 if (isEmpty()) {
126 return OperationResult::Empty;
127 }
128
129 // spを減らしてデータを読み出す
130 sp--;
131 *data = *(internalData + sp);
132 return OperationResult::Success;
133}
134
135} // namespace collection2
136
137#endif
スタック
Definition: stack.hpp:21
Size capacity() const
スタックの全体長を返す
Definition: stack.hpp:73
Stack(Element *const data, const Size &dataSize)
内部データを扱う領域とそのサイズを指定してスタックを初期化
Definition: stack.hpp:106
OperationResult push(const Element &data)
スタックにデータを追加
Definition: stack.hpp:109
bool isEmpty() const
スタックが空かどうか
Definition: stack.hpp:100
OperationResult pop(Element *const data)
スタックからデータを取り出し
Definition: stack.hpp:123
Size amount() const
現在スタック内にあるデータ数を返す
Definition: stack.hpp:82
bool hasSpace() const
スタックに値を追加できるか
Definition: stack.hpp:91
OperationResult
コレクション操作結果
Definition: common.hpp:14