简体   繁体   English

哪个STL C ++容器用于固定大小列表?

[英]Which STL C++ container to use for a fixed size list?

I am having a consuming application which needs to store a maximum of 100 objects in a list to feed to a callback for processing, since it will be redundant to keep old data if the consumer does not catch up. 我有一个使用中的应用程序,该应用程序最多需要在列表中存储100个对象才能馈送给回调进行处理,因为如果使用者不及时处理,则保留旧数据将是多余的。 As new data is arrived, it can simply overwrite the oldest element. 当新数据到达时,它可以简单地覆盖最旧的元素。

I was thinking of using circular buffer container and guessed that it would be deque , but found that it does not use circular list, as well as does not have option to set fixed maximum size. 我当时在考虑使用循环缓冲区容器,并猜测它将是双端队列,但发现它不使用循环列表,也没有设置固定最大大小的选项。

There is a max_size method in dequeue, but documentation says "This is the maximum potential size the container can reach due to system or library implementation limitations." 出队中有一个max_size方法,但是文档说:“这是由于系统或库的实现限制,容器可以达到的最大潜在大小。”

Is there some other container I can use? 我还能使用其他容器吗?

PS : I am using Visual C++ 2010 express PS:我正在使用Visual C ++ 2010 Express

There is no standard library container that does what you want directly. 没有标准库容器可以直接执行您想要的操作。 However, you should take a look at Boost's Circular Buffer Container . 但是,您应该看一下Boost的圆形缓冲区容器 If you can't use Boost, you can at least view its source and redo it. 如果您不能使用Boost,则至少可以查看其来源并重做。

There's boost::circular_buffer . boost :: circular_buffer Then there's 然后有

std::vector<T> vec(size);
vec[i % size] = newelem;

Why not just use a vector with an index that increments mod 100 every time a new object is added? 为什么不只使用索引在每次添加新对象时使mod 100递增的向量?

    #define NUM_ELTS 100
    template < typename T >
    class CircularVector
    { 
    public:
       CircularVector() : idx(0)
       {
          vec = vector<T>(NUM_ELTS);
       }
       void push_back(T& elt)
       {
          vec[ idx++ % NUM_ELTS ] = elt;
       }
    private:
       int idx;
       vector<T> vec;
    };

Something like this, anyway. 无论如何,这样的事情。

I typically roll my own circular buffers with linked lists (I guess it would be the "list" stl container). 我通常使用链接列表来滚动自己的循环缓冲区(我想这将是“列表” stl容器)。 This works well unless you need lots of random access to elements. 除非您需要大量随机访问元素,否则此方法效果很好。 You could write a class containing a linked list and maintain the size yourself (add element at back, if size > threshold {remove element at front}, etc). 您可以编写一个包含链表的类并自己维护大小(如果size> threshold {remove element at front},则在后面添加元素,等等)。 You can also make circular buffers with normal arrays/vectors by maintaining and wrapping head and tail indices, but you might be better off with the boost one mentioned by GMan. 您还可以通过维护和包装头尾索引来制作具有正常数组/向量的循环缓冲区,但是使用GMan提到的boost可能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM