I’m changing some code to use the command pattern and will store command objects in a queue. The commands will need to be executed at specific times and so I will iterate over the list once per second to find commands to execute.
There will be a time associated with each command object and I will check this time against the current time (within a small threshold). So I’ll need to remove the command object from the list if its time matches and then execute it. Generally there will be under 10 commands at any given time. What collection data structure should I use and how do I remove command objects while iterating the list?
I think you want to use a priority queue. This is a container that lets you pull the highest priority item. In your case, “higher priority” is “happens first”.
C++ models a priority queue as the
priority_queuecontainer adapter. This means that there’s some other container inside of it that does the actual storage. This container is usually eithervectorordeque. (Random-access iterators are required.) It defaults tovector. So you can just declare:where
Tis your element andCompareis a function that compares twoTelements and returnstrueif the first is lower priority than the second. If you haveoperator <defined for your typeT, it gets even simpler:queue.push(item);queue.top()queue.pop();Note that
pop()does not return the removed element; it just removes and destructs it.