Reputation: 398
I do have a slot_map<T>
class, which uses a std::vector<T>
to store all the data. I need to have a slot_map<T>::iterator
(and a const_iterator
). I could either do this in a bit ugly way - make the iterator myself and make it work like an interface for the std::vector<T>::iterator
, but that seems like a much more complicated sollution than it has to be (also, I would like to make it clear that the slot_map
iterator must not be just a passed std::vector<T>::iterator
). So, is there any simpler way to take a vector<T>::iterator
and shamefully proclaim it my own?
EDIT: The slot_map data structure uses multiple vectors to store the data and allow inserting and removing in constant time, and also fast iteration. One of the vectors contains all the data (the order of which can change), other one keeps indices to these data and the count of generations at the position (used to decide if the data was marked as removed and the user should not be let to access it) and the last one keeps indices to the indices (yeah, weird), to allow for constant time removal while not breaking the whole structure apart.
What I need to do is just iterate trough the data vector (the objects in the vector can change order during any insertion and erasure, or the entire vector can move because of reallocation - the iterators can of course become invalid because of that), however the iterator has to come from the slot_map
structure and not the vector
.
Upvotes: 3
Views: 1911
Reputation: 74028
It depends on what you want to achieve with such an iterator. If it is just unordered access to the underlying data, a typedef
and associated begin()
/end()
methods is the easiest and cheapest solution, e.g.
template<typename T> class slot_map {
public:
typedef std::vector<T>::const_iterator const_iterator;
const_iterator begin() const { return data.begin(); }
const_iterator end() const { return data.end(); }
// ...
private:
std::vector<T> data;
std::vector<size_t> indexes;
};
Although providing write access is a different matter, since you hold indexes into the data. Writing to the data
vector would most likely invalidate these indexes.
Upvotes: 3