Created
June 27, 2015 17:53
-
-
Save satoruhiga/40c374d9739b61bb47a7 to your computer and use it in GitHub Desktop.
PackedBuffer.h
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
template <typename T, bool (*remove_predicate)(const T&)> | |
class PackedBuffer | |
{ | |
public: | |
PackedBuffer(size_t size) | |
: size_(0) | |
, buffer_(size) | |
{} | |
size_t size() const { return size_; } | |
void clear() { size_ = 0; } | |
T& add() | |
{ | |
T& o = buffer_[size_]; | |
size_++; | |
if (size_ > buffer_.size()) | |
size_ = buffer_.size(); | |
return o; | |
} | |
void add(const T& v) | |
{ | |
T& o = add(); | |
o = v; | |
} | |
void pack() | |
{ | |
for (int i = 0; i < size_; i++) | |
{ | |
const T& o = buffer_[i]; | |
if (!remove_predicate(o)) | |
{ | |
remove_element(i); | |
i--; | |
} | |
} | |
} | |
T& operator[](size_t index) { return buffer_[index]; } | |
const T& operator[](size_t index) const { return buffer_[index]; } | |
private: | |
size_t size_; | |
std::vector<T> buffer_; | |
void remove_element(size_t index) | |
{ | |
std::swap(buffer_[index], buffer_[size_ - 1]); | |
size_--; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment