From df2e05a0c7f59c5a0c54b7cfe2f9869211bef3cc Mon Sep 17 00:00:00 2001 From: cloudnative0x0 <> Date: Wed, 5 Aug 2026 15:50:32 +0300 Subject: [PATCH] queue added. --- queue/Queue.hpp | 59 +++++++++++++++ queue/README.md | 101 ++++++++++++++++++++++++++ queue/stress_test.cpp | 163 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 323 insertions(+) create mode 100644 queue/Queue.hpp create mode 100644 queue/README.md create mode 100644 queue/stress_test.cpp diff --git a/queue/Queue.hpp b/queue/Queue.hpp new file mode 100644 index 0000000..cfd1e28 --- /dev/null +++ b/queue/Queue.hpp @@ -0,0 +1,59 @@ +#ifndef CP_DATA_STRUCTURES_QUEUE_HPP +#define CP_DATA_STRUCTURES_QUEUE_HPP + +#include +#include + +template +class Queue { + std::vector Q; + int head = 0; + int tail = 0; + int count = 0; + +public: + explicit Queue(int capacity) { + if (capacity <= 0) { + throw std::invalid_argument("capacity must be positive"); + } + + Q = std::vector(capacity); + } + + void enqueue(const T& x) { + if (isFull()) { + throw std::overflow_error("Queue is full"); + } + + Q[tail] = x; + tail = (tail + 1) % Q.size(); + count++; + } + + T dequeue() { + if (isEmpty()) { + throw std::underflow_error("Queue is empty"); + } + + T oldHead = Q[head]; + head = (head + 1) % Q.size(); + count--; + + return oldHead; + } + + const T& peek() const { + if (isEmpty()) { + throw std::underflow_error("Queue is empty"); + } + + return Q[head]; + } + + [[nodiscard]] bool isEmpty() const { return count == 0; } + [[nodiscard]] bool isFull() const { return count == Q.size(); } + [[nodiscard]] int size() const { return count; } + [[nodiscard]] int capacity() const { return Q.size(); } +}; + +#endif //CP_DATA_STRUCTURES_QUEUE_HPP diff --git a/queue/README.md b/queue/README.md new file mode 100644 index 0000000..3e3226f --- /dev/null +++ b/queue/README.md @@ -0,0 +1,101 @@ +# Queue + +

+ Русский ・ English +

+ +--- + +## Русский + +Очередь — линейная структура данных, работающая по принципу **FIFO** (First In, First Out): элемент, добавленный первым, извлекается первым. Это полная противоположность стеку. + +Пример: если добавить элементы в порядке `1, 2, 3`, то первым выйдет `1`, затем `2`, затем `3`. Порядок выхода в точности повторяет порядок входа. + +### Внутреннее устройство + +Реализация использует кольцевой буфер на основе вектора `Q`. Три целочисленные переменные управляют состоянием: + +- `head` — индекс первого элемента очереди (откуда читает `dequeue` и `peek`) +- `tail` — индекс свободной ячейки, куда запишется следующий `enqueue` +- `count` — текущее количество элементов + +Использование счётчика `count` позволяет однозначно различить пустую и полностью заполненную очередь даже при `head == tail`. + +При добавлении элемента значение помещается в `Q[tail]`, после чего `tail` сдвигается циклически вперёд: `(tail + 1) % Q.size()`, а `count` увеличивается. При извлечении читается `Q[head]`, затем `head` сдвигается так же, а `count` уменьшается. + +Размер вектора фиксируется при создании очереди и определяет её максимальную ёмкость. Попытка добавить элемент в полную очередь или извлечь из пустой приводит к выбрасыванию стандартных исключений — `std::overflow_error` и `std::underflow_error`. + +### Операции + +| Операция | Сложность | Описание | +|---|---|---| +| `enqueue(x)` | O(1) | добавить элемент в конец очереди | +| `dequeue()` | O(1) | извлечь элемент из начала очереди | +| `peek()` | O(1) | посмотреть первый элемент, не удаляя | +| `isEmpty()` | O(1) | проверка, пуста ли очередь | +| `isFull()` | O(1) | проверка, заполнена ли очередь | +| `size()` | O(1) | текущее количество элементов | +| `capacity()` | O(1) | максимальная ёмкость очереди | + +### Сборка и тестирование + +```bash +cd cmake-build-debug +cmake --build . --target stress_queue +./stress_queue +``` + +Корректность проверяется стресс-тестом — реализация сравнивается с эталонной очередью на `std::deque` на большом числе случайных последовательностей операций. Ожидаемое сообщение при успехе: `All stress tests passed successfully!` + +--- + +## English + +A queue is a linear data structure that follows the **FIFO** principle (First In, First Out): the element inserted first is the first one to be removed. It is the exact opposite of a stack. + +Example: inserting elements in the order `1, 2, 3` will retrieve `1` first, then `2`, then `3`. The order of removal precisely matches the order of insertion. + +### Internal layout + +The implementation uses a circular buffer backed by a vector `Q`. Three integer variables control the state: + +- `head` — index of the first element (where `dequeue` and `peek` read from) +- `tail` — index of the free cell where the next `enqueue` will write +- `count` — current number of elements + +The counter `count` makes it possible to distinguish between an empty queue and a full queue, even when `head == tail`. + +When an element is added, the value is stored in `Q[tail]`, then `tail` advances circularly: `(tail + 1) % Q.size()`, and `count` increases. When an element is removed, `Q[head]` is read, then `head` advances in the same way, and `count` decreases. + +The vector size is fixed at construction and defines the maximum capacity. Trying to enqueue into a full queue or dequeue from an empty one throws standard exceptions — `std::overflow_error` and `std::underflow_error` respectively. + +### Operations + +| Operation | Complexity | Description | +|---|---|---| +| `enqueue(x)` | O(1) | add an element to the back of the queue | +| `dequeue()` | O(1) | remove and return the front element | +| `peek()` | O(1) | return the front element without removing it | +| `isEmpty()` | O(1) | check whether the queue is empty | +| `isFull()` | O(1) | check whether the queue is at capacity | +| `size()` | O(1) | current number of elements | +| `capacity()` | O(1) | maximum capacity of the queue | + +### Build and test + +```bash +cd cmake-build-debug +cmake --build . --target stress_queue +./stress_queue +``` + +Correctness is verified by a stress test — the implementation is compared against a reference queue based on `std::deque` over a large number of randomized operation sequences. On success, the program prints: `All stress tests passed successfully!` + +--- + +
+ +> Очередь не смотрит на важность, не слышит просьб пропустить вперёд. Она знает только одно: кто пришёл раньше, тот и уйдёт раньше. В этом её слепая справедливость. +> +> *A queue does not look at importance, nor does it hear pleas to skip ahead. It knows only one thing: whoever came first leaves first. In that lies its blind justice.* \ No newline at end of file diff --git a/queue/stress_test.cpp b/queue/stress_test.cpp new file mode 100644 index 0000000..587364c --- /dev/null +++ b/queue/stress_test.cpp @@ -0,0 +1,163 @@ +#include +#include +#include +#include + +#include "Queue.hpp" + +template +class ReferenceQueue { + std::deque data; + int cap; +public: + explicit ReferenceQueue(int capacity) : cap(capacity) { + if (capacity <= 0) throw std::invalid_argument("capacity must be positive"); + } + + bool isEmpty() const { return data.empty(); } + bool isFull() const { return (int)data.size() == cap; } + + void enqueue(const T& x) { + if (isFull()) throw std::overflow_error("Queue is full"); + data.push_back(x); + } + + T dequeue() { + if (isEmpty()) throw std::underflow_error("Queue is empty"); + T val = data.front(); + data.pop_front(); + return val; + } + + const T& peek() const { + if (isEmpty()) throw std::underflow_error("Queue is empty"); + return data.front(); + } + + int size() const { return (int)data.size(); } + int capacity() const { return cap; } +}; + +int main() { + std::cout << "Starting stress test..." << std::endl; + + const int CAPACITY = 30; + const int ITERATIONS = 1000; + const int OPS_PER_ITERATION = 50; + + std::mt19937 rng(42); + std::uniform_int_distribution opDist(0, 2); // 0:enqueue, 1:dequeue, 2:peek+size + std::uniform_int_distribution valueDist(0, 999); + + try { + for (int iter = 0; iter < ITERATIONS; ++iter) { + Queue testQ(CAPACITY); + ReferenceQueue refQ(CAPACITY); + + for (int op = 0; op < OPS_PER_ITERATION; ++op) { + int action = opDist(rng); + + switch (action) { + case 0: { // enqueue + bool testFull = testQ.isFull(); + bool refFull = refQ.isFull(); + if (testFull != refFull) { + std::cerr << "ERROR: isFull mismatch at iter=" << iter + << " op=" << op << "\n"; + return 1; + } + + if (!testFull) { + int val = valueDist(rng); + testQ.enqueue(val); + refQ.enqueue(val); + } else { + try { + testQ.enqueue(0); + std::cerr << "ERROR: expected overflow_error at iter=" << iter + << " op=" << op << "\n"; + return 1; + } catch (const std::overflow_error&) {} + } + break; + } + + case 1: { // dequeue + bool testEmpty = testQ.isEmpty(); + bool refEmpty = refQ.isEmpty(); + if (testEmpty != refEmpty) { + std::cerr << "ERROR: isEmpty mismatch at iter=" << iter + << " op=" << op << "\n"; + return 1; + } + + if (!testEmpty) { + int testVal = testQ.dequeue(); + int refVal = refQ.dequeue(); + if (testVal != refVal) { + std::cerr << "ERROR: dequeue value mismatch at iter=" << iter + << " op=" << op << ": test=" << testVal + << " ref=" << refVal << "\n"; + return 1; + } + } else { + try { + testQ.dequeue(); + std::cerr << "ERROR: expected underflow_error at iter=" << iter + << " op=" << op << "\n"; + return 1; + } catch (const std::underflow_error&) {} + } + break; + } + + case 2: { // peek + check size + bool testEmpty = testQ.isEmpty(); + bool refEmpty = refQ.isEmpty(); + if (testEmpty != refEmpty) { + std::cerr << "ERROR: isEmpty mismatch (peek) at iter=" << iter + << " op=" << op << "\n"; + return 1; + } + if (!testEmpty) { + int testPeek = testQ.peek(); + int refPeek = refQ.peek(); + if (testPeek != refPeek) { + std::cerr << "ERROR: peek mismatch at iter=" << iter + << " op=" << op << ": test=" << testPeek + << " ref=" << refPeek << "\n"; + return 1; + } + } + + if (testQ.size() != refQ.size()) { + std::cerr << "ERROR: size mismatch at iter=" << iter + << " op=" << op << ": test=" << testQ.size() + << " ref=" << refQ.size() << "\n"; + return 1; + } + if (testQ.capacity() != CAPACITY) { + std::cerr << "ERROR: capacity mismatch at iter=" << iter << "\n"; + return 1; + } + break; + } + + default: + break; + } + } + } + + std::cout << "All stress tests passed successfully!" << std::endl; + return 0; + } + catch (const std::exception& e) { + std::cerr << "Unexpected exception: " << e.what() << std::endl; + return 1; + } + catch (...) { + std::cerr << "Unknown exception" << std::endl; + return 1; + } +}