1

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 Answer 1

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.

1
  • I'm sorry, I'm confused what you mean by wrapper class. Feb 26, 2015 at 2:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.