Queue of class objects

2019-09-05 22:34发布

问题:

Given the following queue implementation below, I was wondering whether it would be possible to access the class' members after it is popped from the queue. Basically I am supposed to keep track of how long an item is held in a queue until it is popped and I'm kind of lost on how to do that. The time is represented as the number of iterations of a specific loop(not shown below)

#include <queue>

class Plane
{
   public:
     Plane() {}
};

std::queue<Plane> landing;

int main()
{
   landing.push(Plane());
}

回答1:

You probably want to put the item in a wrapper class before putting it in the queue. Have the wrapper class include a counter that you set to zero when you enter the item in the queue, and increment at every iteration of the loop. When you pop it out, the counter tells you its age.

The wrapper class would look something like this:

template <class T>
class timed { 
    T item;
    unsigned timer;
public:
    timed(T const &t) : item(t), timer(0) {}
    void tick() { ++ timer; }
    unsigned elapsed() { return timer; }
    operator T() { return item; }
};

Then instead of a queue<Plane>, you'd create a queue<timed<plane>>. Each timer tick, you'd walk through your queue and call tick on each item. Oh, but since you want to access all the items, not just push and pop, you probably want to use an std::deque<timed<plane>> instead.