The algorithm I'm implementing has the structure:
while C is not empty
select a random entry e from C
if some condition on e
append some new entries to C (I don't care where)
else
remove e from C
It's important that each iteration of the loop e is chosen at random (with uniform probability).
Ideally the select, append and remove steps are all O(1).
If I understand correctly, using std::list the append and remove steps will be O(1) but the random selection will be O(n) (e.g., using std::advance as in this solution).
And std::deque and std::vector seem to have complementary O(1) and O(n) operations.
I'm guessing that std::set will introduce some O(log n) complexity.
Is there any stl container that supports all three operations that I need in constant time (or amortized constant time)?
No such container exists if element order should be consistent. You can get
O(1)selection and (amortized) append withvectorordeque, but removal isO(n). You can getO(1)(average case) insertion and removal withunordered_map, but selection isO(n).listgets youO(1)for append and removal, butO(n)selection. There is no container that will get youO(1)for all three operations. Figure out the least commonly used one, choose a container which works for the others, and accept the one operation will be slower.If the order of the container doesn't matter per use 3365922's comment, the removal step could be done in
O(1)on avector/dequebyswapping the element to be removed with the final element, then performing apop_back.