Sliding buffer

I'm not sure if this is the correct term, but it's what I would call it. I'm trying to implement a "sliding buffer" to hold n number of elements from a file. For example, let's say n = 5, and input = {9879865225721}.

At first the buffer would contain {98798}
Second iteration: {87986}
Third iteration : {79865}
Fourth iteration: {98652}
...
Last iteration : {25721}

As you can see it drops the first element each time, "slides" to the left by one, and then adds a new element to the end. I'm not sure how to go about doing this. Vector seems like it would be really slow for this.
What I see "sliding" here is an index to the head position in the buffer. A "circular" design may work here.
buf = 98798, idx = 0;
Overwrite buf[0] and increment idx
buf = 68798, idx = 1
You would write this to the display by starting at buf[idx] and looping around back to buf[idx-1] as last diplayed.

EDIT: Last sentence poorly phrased. Consider the buffer as starting at buf[idx] and ending at buf[idx-1] (circularly).
Last edited on

buf = 98798, idx = 0;
Overwrite buf[0] and increment idx
buf = 68798, idx = 1


I'm not sure what's happening here. It looks like all you did was replace the first element, and increment idx? This doesn't actually "slide" the buffer over. It should keep the last n-1 elements and move them all over one place and replace the nth element with the next non-buffered element. And as writing this I think I just figured it out. I'll see what breaks this time
Deque with a custom insertion function that would also limit the max size by removing the first elements should work. Or i think Boost has a circular list container (or it is not hard to do even in C with a simple array and position index(es) to firstValPos and lastValPos if you know the size in advance)
I dont think you need a circular buffer (seems it would be infinite), and vector should be fine since access is constant and traversal is linear.
1
2
3
4
5
6
7
8
9
10
11
int t[] = {9,8,7,9,8,6,5,2,2,5,7,2,1};
	std::vector<int> v(t, t+13);
	std::vector<int>::iterator it;
	for(it= v.begin();  (it+4) !=v.end(); ++it)
	{
		for(int i = 0; i < 5; ++i)
		{
			std::cout<<*(it+i);
		}
		std::cout<<std::endl;
	}
Topic archived. No new replies allowed.