简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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