C++ equivalent of Python's deque with maxlen - sliding window In Python it is really easy to get sliding window functionality using a deque with maxlen:

from collections import deque
deck = deque(maxlen=4)
deck.append(0x01)
deck.append(0x02)
deck.append(0x03)
deck.append(0x04)
deck.append(0x05)
for item in deck:
    print(item)  # outputs 2, 3, 4, 5


This does two things - it grows until maxsize and then once maxsize has been reached items drop off the deque.

I wanted something similar in C++ and wrote the following (note, I know C++ has a deque, but I couldn't see how to reserve the size):

template &lt;typename T&gt;
auto rotate_push(std::vector&lt;T&gt; &amp;container, const T&amp; val) -&gt; void
{
    if (container.size() &lt; container.capacity()) {
        container.resize(deck.size() + 1);
    }
    else {
        std::rotate(container.begin(), container.begin() + 1, container.end());
    }

    container[container.size() - 1] = val;
}

auto deck = std::vector&lt;int&gt;();
deck.reserve(4);
rotate_push(deck, 1);
rotate_push(deck, 2);
rotate_push(deck, 3);
rotate_push(deck, 4);
rotate_push(deck, 5);

for (auto const &amp;item : deck) {
    printf("%d\n", item); // outputs 2, 3, 4, 5
}


My Questions are:


Are the implementations basically equivalent (If not then why)
Is there a better custom implementation
Is there a easier/pre-existing implementation using STL
Is there a easier/pre-existing implementation using other
Is there a more performant implementation


Answers:


No, they have different push complexity [by Johnbot]
Use a free function or wrap std::deque [by Johnbot]
(Un-answered)
Boost Circular Buffer [by ratchet freak]
Circular Buffer [by ratchet freak]
You will get better performance using a ring buffer. (With an existing implementation in Boost)

This will keep an extra set of indexes into the buffer to specify the start and end of where the data is and wrap around automatically.