Search code examples
c++c++11fifobufferingdata-stream

Is list better than vector when we need to store "the last n items"?


There are a lot of questions which suggest that one should always use a vector, but it seems to me that a list would be better for the scenario, where we need to store "the last n items"

For example, say we need to store the last 5 items seen: Iteration 0:

3,24,51,62,37,

Then at each iteration, the item at index 0 is removed, and the new item is added at the end:

Iteration 1:

24,51,62,37,8

Iteration 2:

51,62,37,8,12

It seems that for this use case, for a vector the complexity will be O(n), since we would have to copy n items, but in a list, it should be O(1), since we are always just chopping off the head, and adding to the tail each iteration.

Is my understanding correct? Is this the actual behaviour of an std::list ?


Solution

  • Neither. Your collection has a fixed size and std::array is sufficient.

    The data structure you implement is called a ring buffer. To implement it you create an array and keep track of the offset of the current first element.

    When you add an element that would push an item out of the buffer - i.e. when you remove the first element - you increment the offset.

    To fetch elements in the buffer you add the index and the offset and take the modulo of this and the length of the buffer.