patternpythonMinor
C++ equivalent of Python's deque with maxlen - sliding window
Viewed 0 times
equivalentmaxlenwithslidingdequepythonwindow
Problem
In Python it is really easy to get sliding window functionality using a
This does two things - it grows until
I wanted something similar in C++ and wrote the following (note, I know C++ has a
My Questions are:
Answers:
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, 5This 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
auto rotate_push(std::vector &container, const T& val) -> void
{
if (container.size() ();
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]
Solution
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.
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.
Context
StackExchange Code Review Q#108250, answer score: 4
Revisions (0)
No revisions yet.