|
|
1.1 root 1: //
2: // nono
1.1.1.4 root 3: // Copyright (C) 2020 nono project
4: // Licensed under nono-license.txt
1.1 root 5: //
6:
1.1.1.3 root 7: #pragma once
8:
1.1 root 9: #include "header.h"
10: #include <vector>
11:
12: // 固定長キュー
13: // std::queue では出来ないことがいくつかあるので仕方なく車輪の再開発。
1.1.1.6 root 14: // std::vector を親に使っているが empty() と Empty() の動作が異なるなど
15: // しているため public にせず private 継承している。
1.1 root 16: //
17: // T 型で上限 capacity 個のキュー。
18: // スレッドセーフではない。
19: template <typename T, int capacity>
1.1.1.7 ! root 20: class FixedQueue : private std::vector<T>
1.1 root 21: {
1.1.1.6 root 22: using inherited = std::vector<T>;
1.1 root 23: public:
24: // コンストラクタ
25: FixedQueue()
1.1.1.6 root 26: : inherited(capacity)
1.1 root 27: {
28: }
29:
30: // デストラクタ
31: virtual ~FixedQueue() {
32: }
33:
34: // 空にする
35: void Clear() {
36: start = 0;
37: length = 0;
38: }
39:
1.1.1.6 root 40: // 空きがあれば追加して true を返す。
41: // 空きがなければ何もせず false を返す。
1.1 root 42: bool Enqueue(T val) {
1.1.1.6 root 43: if (IsFull()) {
44: return false;
45: } else {
46: (*this)[(start + length) % capacity] = val;
1.1 root 47: length++;
48: return true;
49: }
50: }
51:
1.1.1.6 root 52: // 空きがなければ古いのを捨てて追加する。
53: void EnqueueForce(T val) {
54: if (IsFull()) {
55: Dequeue();
56: }
57: Enqueue(val);
58: }
59:
1.1 root 60: // 取り出し
61: // 要素が1つ以上あれば *outp に取り出して true を返す。
62: // キューが空なら false を返す。
63: bool Dequeue(T *outp) {
64: if (length > 0) {
65: // 1つ以上あれば取り出し
1.1.1.6 root 66: *outp = (*this)[start];
1.1 root 67: start = (start + 1) % capacity;
68: length--;
69: return true;
70: } else {
71: return false;
72: }
73: }
74:
75: // 取り出し
76: // 先頭の要素を取り出して返す。
1.1.1.6 root 77: // キューが空の時に呼ぶと T() が返る。
1.1 root 78: T Dequeue() {
79: if (length > 0) {
1.1.1.6 root 80: T val = (*this)[start];
1.1 root 81: start = (start + 1) % capacity;
82: length--;
1.1.1.6 root 83: return val;
84: } else {
85: return T();
1.1 root 86: }
87: }
88:
89: // 現在の要素数を取得
90: uint Length() const {
91: return length;
92: }
93:
1.1.1.6 root 94: // 要素が空なら true を返す
95: bool Empty() const {
96: return (length == 0);
97: }
98:
1.1.1.2 root 99: // 要素が一杯なら true を返す
100: bool IsFull() const {
1.1.1.6 root 101: return (Length() >= capacity);
1.1.1.2 root 102: }
103:
1.1 root 104: // 要素を覗き見る。
105: // idx は 0 .. length-1 までで、0 がキューの先頭。
1.1.1.3 root 106: T Peek(int idx) const {
1.1 root 107: // XXX 範囲チェックすべきだがとりあえず
1.1.1.6 root 108: return (*this)[(start + idx) % capacity];
109: }
110:
111: // 要素数を返す
112: constexpr int Capacity() const {
113: return capacity;
1.1 root 114: }
115:
116: private:
1.1.1.5 root 117: uint start {}; // 開始位置
118: uint length {}; // 現在有効な長さ
1.1 root 119: };
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.