Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Forked from anonymous/gist:2d80c4e33068359e625f
Last active August 29, 2015 14:02
Show Gist options
  • Save pyrtsa/6418f10b7e19c9f7c27c to your computer and use it in GitHub Desktop.
Save pyrtsa/6418f10b7e19c9f7c27c to your computer and use it in GitHub Desktop.
#include <vector>
#include <memory>
#include <cassert>
template<typename T>
struct idx_vector {
typedef int index;
std::vector<std::unique_ptr<T>> pointers_;
std::vector<index> free_indices_;
index add(T x) {
if (free_indices_.empty()) {
index i = free_indices_.back();
free_indices_.pop_back();
pointers_[i].swap(p);
return i;
} else {
pointers_.push_back(std::make_unique<T>(std::move(x)));
return static_cast<index>(pointers_.size() - 1);
}
}
bool has(index i) {
return i < pointers_.size() && pointers_[i];
}
T get(index i) {
if (has(i)) {
return *pointers_[i];
} else {
assert(false);
return {};
}
}
void remove(index i) { // invalidates index, but not other indices
if (has(i)) {
pointers_[i] = nullptr;
free_indices_.push_back(i);
} else {
assert(false);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment