How do you iterate backward over circular buffer without a conditional?

萝らか妹 提交于 2020-01-22 17:33:28

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/3437477/how-do-you-iterate-backward-over-circular-buffer-without-a-conditional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!