类对象的队列 [英] Queue of class objects

查看:107
本文介绍了类对象的队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面给出了下面的队列实现,我想知道在从队列中弹出类成员之后是否可以访问它。基本上,我应该跟踪一个项目在队列中持有多长时间,直到它弹出,我很失去如何做到这一点。时间表示为特定循环的迭代次数(未在下面示出)

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());
}


推荐答案

项目放在包装器类中,然后再放入队列。让包装器类包含一个计数器,当您在队列中输入项目时将其设置为零,并在循环的每次迭代时递增。

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.

包装类看起来像这样:

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; }
};

而不是队列< Plane> ,您将创建一个队列< timed< plane>> 。每个计时器滴答,你会走过你的队列,并在每个项目上调用 tick 。哦,但是因为你想访问所有的项目,而不仅仅是push和pop,你可能想使用 std :: deque< timed< plane>>

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.

这篇关于类对象的队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆