I am currently looking for container that provides some inserting (insert or push_back) and some removing (erase, pop_back is not sufficient) methods, and that does not invalidate iterators nor pointers when calling these two methods.
More clearly, I want a set of elements where I can add an element (I do not care where), and where I can remove any element (so I do care where). In addition, I would have external pointers to specific elements, and I want them to remain valid if I add or remove an element from the set.
There are, to my knowledge, two standard containers that answer my needs : set
and list
. However, generally speaking, I do not like to use such containers for such simple needs. Since a list
is involving pointers internally and does not provide random access to its elements, I think it is not a good choice. A set
has random access to its elements, but is also involving pointers, and the random access itself is not done in constant time. I think that a set
would be a better solution than a list
, but I have thought about something else.
What about a simple vector that does not try to keep the elements contiguous when an element is removed ? When removing an element in the middle of this container, its position would be empty, and nothing else would happen. This way, no iterator or pointer would be invalidated. Also, when adding an element, the container would search for an empty position, and use a simple push_back
if there is no such hole.
Obviously, since push_back
can invalidate iterators with a vector
, I would use a deque
as the basis of implementation. I would also use some sort of stack to keep track of the holes from removing elements. This way, adding, removing, and accessing an element would be done in constant time, in addition to satisfying my no-invalidation needs.
However, there is still one problem : when iterating over this container or simply accessing an element by index we would need to take the holes into account. And that is where the problems start to surpass the advantages.
Hence my question : what do you think about my idea for that container ?
More importantly, what would you use for my original problem, a set
, a list
or something else ?
Also, if you have a nice and clean solution to the last problem (iterating over my container), feel free to show me.