Skip to content

Instantly share code, notes, and snippets.

@ror3d
Last active June 13, 2017 07:56
Show Gist options
  • Save ror3d/1daf2149ec54eaee470b625c04f7a2af to your computer and use it in GitHub Desktop.
Save ror3d/1daf2149ec54eaee470b625c04f7a2af to your computer and use it in GitHub Desktop.
#include <vector>
template<class T, unsigned buffer_size=500>
class circular_queue
{
public:
unsigned front = 0;
unsigned back = 0;
unsigned count = 0;
std::vector<T> items;
circular_queue<T>()
: items(buffer_size)
{
}
~circular_queue<T>()
{
}
void push(const T& item)
{
if (count >= items.size())
{
std::vector<T> newQueue(items.size() * 2);
unsigned n = items.size() - front;
memcpy(newQueue.data(), &(items[front]), n * sizeof(T));
if (front > 0)
{
memcpy(&(newQueue[n]), items.data(), front * sizeof(T));
}
front = 0;
back = items.size();
items.swap(newQueue);
}
memcpy(&items[back], &item, sizeof(T));
count++;
back++;
if (back >= items.size())
{
back -= items.size();
}
}
void pop(T& item)
{
assert(!empty());
memcpy(&item, &items[front], sizeof(T));
count--;
front++;
if (front >= items.size())
{
front -= items.size();
}
}
T& peek()
{
assert(!empty());
return items[front];
}
bool empty() const
{
return count == 0;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment