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 <typename T>
auto rotate_push(std::vector<T> &container, const T& val) -> void
{
if (container.size() < 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<int>();
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 &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]