Last active
August 10, 2017 00:09
-
-
Save LeftofZen/88af6de4343b4047333e1776edd4bca1 to your computer and use it in GitHub Desktop.
An efficient data structure for caching a small number of tokens
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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