循環Queue
Circular bufferは要素をずらさず空いた位置を再利用します。
循環Queueとは?
Circular bufferは要素をずらさず空いた位置を再利用します。
First-in-first-out処理を実装します。
重要なポイント
- 操作より先にinvariantを定義します。
- 空・満杯・allocation失敗を処理します。
- 計算量とownershipを一緒に評価します。
CとC++のコード例
C
main.c
#include <stdio.h>
typedef struct {
int data[4];
int head;
int size;
} Queue;
int push(Queue *queue, int value) {
if (queue->size == 4) return 0;
int tail = (queue->head + queue->size) % 4;
queue->data[tail] = value;
++queue->size;
return 1;
}
int pop(Queue *queue, int *value) {
if (queue->size == 0) return 0;
*value = queue->data[queue->head];
queue->head = (queue->head + 1) % 4;
--queue->size;
return 1;
}
int main(void) {
Queue queue = {{0}, 0, 0};
int value;
push(&queue, 7);
push(&queue, 9);
pop(&queue, &value);
printf("%d\n", value);
}
7
C++
main.cpp
#include <iostream>
#include <queue>
int main() {
std::queue<int> values;
values.push(7);
values.push(9);
std::cout << values.front() << '\n';
values.pop();
}
7
CとC++の比較
Cはheadとsizeをmoduloで管理し、std::queueはfront、push、popを提供します。
C
構造体と操作は分離され、allocationは明示的です。
C++
classとcontainerがinvariantとresourceを管理します。
練習課題
両方を実行して変更し、言語ごとの保証を確認します。
- 空と容量境界をテストします。
- cleanupを実装しleakを確認します。
- standard containerと比較します。