-
-
Save pyrtsa/6418f10b7e19c9f7c27c to your computer and use it in GitHub Desktop.
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 <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