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_queue
container adapter. This means that there's some other container inside of it that does the actual storage. This container is usually either vector
or deque
. (Random-access iterators are required.) It defaults to vector
. So you can just declare:
std::priority_queue<T, vector<T>, Compare> queue;
where T
is your element and Compare
is a function that compares two T
elements and returns true
if the first is lower priority than the second. If you have operator <
defined for your type T
, it gets even simpler:
std::priority_queue<T> queue;
queue.push(item);
queue.top()
queue.pop();
Note that pop()
does not return the removed element; it just removes and destructs it.