added basic, based on my own ADT c implementation of a queue
This commit is contained in:
93
include/queue.h
Normal file
93
include/queue.h
Normal file
@@ -0,0 +1,93 @@
|
||||
#ifndef QUEUE_H
|
||||
#define QUEUE_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <new>
|
||||
#include <print>
|
||||
#include <format>
|
||||
#include <expected>
|
||||
|
||||
#define DEFAULT_QUEUE_SIZE 4
|
||||
|
||||
enum class QueueErr {
|
||||
ok,
|
||||
bad_alloc,
|
||||
empty,
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
requires std::formattable<T, char>
|
||||
class Queue {
|
||||
private:
|
||||
uint64_t len;
|
||||
uint64_t cap;
|
||||
uint64_t head;
|
||||
uint64_t tail;
|
||||
T *data;
|
||||
public:
|
||||
Queue();
|
||||
Queue(uint64_t size);
|
||||
|
||||
~Queue();
|
||||
|
||||
QueueErr enqueue(T value);
|
||||
|
||||
std::expected<T, QueueErr> peek();
|
||||
|
||||
std::expected<T, QueueErr> unqueue();
|
||||
|
||||
void display();
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
requires std::formattable<T, char>
|
||||
Queue<T>::Queue() {
|
||||
this->cap = 0;
|
||||
this->len = 0;
|
||||
this->head = 0;
|
||||
this->tail = 0;
|
||||
this->data = new T[DEFAULT_QUEUE_SIZE];
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
requires std::formattable<T, char>
|
||||
Queue<T>::Queue(uint64_t size) {
|
||||
this->cap = 0;
|
||||
this->len = 0;
|
||||
this->head = 0;
|
||||
this->tail = 0;
|
||||
this->data = new T[size];
|
||||
|
||||
}
|
||||
|
||||
|
||||
template <typename T>
|
||||
requires std::formattable<T, char>
|
||||
QueueErr Queue<T>::enqueue(T value) {
|
||||
if (this->len >= this->cap) {
|
||||
uint64_t new_cap = this->cap * 2;
|
||||
T *tmp;
|
||||
|
||||
try {
|
||||
T *tmp = new T[new_cap];
|
||||
} catch(const std::bad_alloc& e) {
|
||||
return 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;
|
||||
}
|
||||
|
||||
this->data[this->head] = value;
|
||||
this->len++;
|
||||
this->head = (this->head + 1) % this->cap;
|
||||
}
|
||||
#endif // !QUEUE_H
|
||||
Reference in New Issue
Block a user