How do you iterate backward over circular buffer w

2019-04-04 13:15发布

Iterating forward through a circular buffer without using a conditional is easy with the remainder operator...

iterator = (iterator + 1) % buffer_size;

I can't for the life of me figure out the reverse operation, iterating backward.

2条回答
劳资没心,怎么记你
2楼-- · 2019-04-04 14:00

Does iterator = (iterator + buffer_size - 1) % buffer_size work for you? Go one less than all the way around.

查看更多
We Are One
3楼-- · 2019-04-04 14:02

Borealid's answer works. (note: iterator is set to 0 initially).

Another solution is

iterator = buffer_size - 1 - (buffer_size - iterator) % buffer_size with iterator set to buffer_size initially.

查看更多
登录 后发表回答