How do I code a simple integer circular buffer in C/C++?

后端 未结 4 1274
长发绾君心
长发绾君心 2021-02-05 08:54

I see a lot of templates and complicated data structures for implementing a circular buffer.

How do I code a simple integer circular buffer for 5 numbers?

I\

4条回答
  •  执念已碎
    2021-02-05 09:44

    Take an array, arr, an index idx, and a counter, num.

    To insert foo, say arr[idx++] = foo; idx %= buffer_len; num++;.

    To read out an item into foo, say foo = arr[(idx-num)%buffer_len]; num--;.

    Add boundary checks.

提交回复
热议问题