高效的通知单 [英] Efficient circular list

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

问题描述

我想要一个简单而有效的循环缓冲区/队列。如果我使用 std :: vector ,则必须这样做:

I want a simple yet efficient circular buffer/queue. If I use std::vector, I have to do this:

if ( v.size() >= limit ) {
    std::vector<int> it = v.begin();
    v.insert( it, data );
    v.erase( it+1 );
}

有没有更简单的解决方案?

Is there any simpler solution?

推荐答案

您要保持缓冲区的大小,覆盖较早的项目。随着时间的流逝,只需覆盖旧的。如果您想处理nItems<限制,那么您将需要处理这个问题,这只是使用取模插入固定大小缓冲区的简单示例。

You want to maintain the size of the buffer, overwriting older items. Just overwrite the old ones as time goes on. If you want to deal with the case where nItems < limit, then you would need to deal with that, this is just a simple example of using modulo to insert into a fixed size buffer.

std::vector<int> data(10);

for (int i = 0 ; i < 100 ; ++i)
{
    data[i%10] = i;
}

for (std::vector<int>::const_iterator it = data.begin() ; it !=data.end(); ++it)
{
     std::cout << *it << std::endl;
}

该插入方法会将最后10个元素保留在缓冲区中。

That method of insertion will keep the last 10 elements in the buffer.

这篇关于高效的通知单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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