Skip to content

Instantly share code, notes, and snippets.

@LeftofZen
Last active August 10, 2017 00:09
Show Gist options
  • Save LeftofZen/88af6de4343b4047333e1776edd4bca1 to your computer and use it in GitHub Desktop.
Save LeftofZen/88af6de4343b4047333e1776edd4bca1 to your computer and use it in GitHub Desktop.
An efficient data structure for caching a small number of tokens
#include <array>
#include <cstddef>
#include <stack>
template <typename T, size_t SIZE>
class CarPark
{
public:
CarPark()
{
// Setup initial free spaces
for (size_t i = SIZE; i > 0; --i)
{
mFreeSpaces.push(i - 1);
}
}
const size_t& Park(const T* const t)
{
size_t ticket = mFreeSpaces.top();
mSpaces.at(ticket) = t;
mFreeSpaces.pop();
return ticket;
}
const T* const DePark(size_t ticket)
{
const T* const result = mSpaces.at(ticket);
mSpaces.at(ticket) = nullptr;
mFreeSpaces.push(ticket);
return result;
}
private:
std::array<const T*, SIZE> mSpaces { { nullptr } };
std::stack<size_t> mFreeSpaces;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment