added dequeue and peek, easy

This commit is contained in:
2026-03-17 20:57:07 -06:00
parent 51600344dd
commit fa154fbd5f

View File

@@ -34,7 +34,7 @@ public:
std::expected<T, QueueErr> peek(); std::expected<T, QueueErr> peek();
std::expected<T, QueueErr> unqueue(); std::expected<T, QueueErr> dequeue();
void display(); void display();
}; };
@@ -89,5 +89,62 @@ QueueErr Queue<T>::enqueue(T value) {
this->data[this->head] = value; this->data[this->head] = value;
this->len++; this->len++;
this->head = (this->head + 1) % this->cap; this->head = (this->head + 1) % this->cap;
return QueueErr::ok;
}
template <typename T>
requires std::formattable<T, char>
std::expected<T, QueueErr> Queue<T>::dequeue() {
if (this->len == 0) {
return std::unexpected(QueueErr::empty);
}
if (this->cap > DEFAULT_QUEUE_SIZE && this->cap / 4 > this->len) {
uint64_t new_cap = this->cap / 2;
if (new_cap < DEFAULT_QUEUE_SIZE) {
new_cap = DEFAULT_QUEUE_SIZE;
}
T *tmp;
try {
tmp = new T[new_cap];
} catch(const std::bad_alloc& e) {
return std::unexpected(QueueErr::bad_alloc);
}
for (uint64_t i = 0; i < this->len; i++) {
uint64_t index = (this->tail) % this->cap;
tmp[i] = this->data[index];
}
delete[] this->data;
this->data = tmp;
this->cap = new_cap;
this->tail = 0;
this->head = this->len;
}
T out;
out = this->data[this->tail];
this->len--;
this->tail = (this->tail + 1) % this->cap;
return out;
}
template <typename T>
requires std::formattable<T, char>
std::expected<T, QueueErr> Queue<T>::peek() {
if (this->len == 0) {
return std::unexpected(QueueErr::empty);
}
T out;
out = this->data[this->tail];
this->len--;
this->tail = (this->tail + 1) % this->cap;
return out;
} }
#endif // !QUEUE_H #endif // !QUEUE_H