开发者

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

开发者 https://www.devze.com 2023-02-22 02:38 出处:网络
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 co

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. 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."

Is there some other container I can use?

PS : I am using 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. If you can't use Boost, you can at least view its source and redo it.


There's 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?

    #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). 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). 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消