BLT/include/blt/std/queues.h

121 lines
3.2 KiB
C
Raw Normal View History

2022-12-26 00:31:00 -05:00
/*
* Created by Brett on 26/12/22.
* Licensed under GNU General Public License V3.0
* See LICENSE file for license detail
*/
#ifndef BLT_QUEUES_H
#define BLT_QUEUES_H
2022-12-26 23:36:34 -05:00
/**
* Do no use any queue in this file. They are slower than std::queue.
*/
2022-12-26 00:31:00 -05:00
namespace BLT {
template<typename T>
struct node {
T t;
node* next;
2022-12-26 00:57:11 -05:00
node(const T& t, node* next){
this->t = t;
this->next = next;
}
2022-12-26 00:31:00 -05:00
};
template<typename T>
class flat_queue {
2022-12-26 01:10:37 -05:00
private:
int size = 16;
int insertIndex = 0;
T* data = new T[size];
/**
* Expands the internal array to the new size, copying over the data and shifting its minimal position to index 0
* and deletes the old array from memory.
* @param newSize new size of the internal array
*/
2022-12-26 01:10:37 -05:00
void expand(int newSize){
auto tempData = new T[newSize];
for (int i = 0; i < insertIndex; i++)
tempData[i] = data[i];
2022-12-26 01:10:37 -05:00
delete[] data;
data = tempData;
size = newSize;
}
public:
void push(const T& t) {
if (insertIndex >= size){
expand(size * 2);
}
data[insertIndex++] = t;
}
/**
* Warning does not contain runtime error checking!
* @return the element at the "front" of the queue.
*/
2022-12-26 01:10:37 -05:00
[[nodiscard]] const T& front() const {
return data[insertIndex-1];
2022-12-26 01:10:37 -05:00
}
void pop() {
// TODO: throw exception when popping would result in a overflow?
// I didn't make it an exception here due to not wanting to import the class.
if (isEmpty())
return;
insertIndex--;
}
bool isEmpty(){
return insertIndex <= 0;
2022-12-26 01:10:37 -05:00
}
2023-01-05 11:49:45 -05:00
int getInsertIndex(){
return insertIndex;
}
2022-12-26 01:10:37 -05:00
~flat_queue() {
delete[](data);
}
2022-12-26 00:31:00 -05:00
};
// avoid this. it is very slow.
2022-12-26 00:31:00 -05:00
template<typename T>
class node_queue {
private:
node<T>* head;
public:
2022-12-26 01:10:37 -05:00
void push(const T& t) {
2022-12-26 00:31:00 -05:00
if (head == nullptr)
2022-12-26 01:02:46 -05:00
head = new node<T>(t, nullptr);
else
head = new node<T>(t, head);
2022-12-26 00:31:00 -05:00
}
2022-12-26 00:55:49 -05:00
[[nodiscard]] const T& front() const {
2022-12-26 00:31:00 -05:00
return head->t;
}
void pop() {
auto nextNode = head->next;
delete(head);
head = nextNode;
}
~node_queue() {
auto next = head;
while (next != nullptr){
auto nextNode = next->next;
delete(next);
next = nextNode;
}
}
};
}
#endif //BLT_QUEUES_H