如何在 C/C++ 中编写一个简单的整数循环缓冲区?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3621956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:17:49  来源:igfitidea点击:

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

c++carrayscircular-buffer

提问by T.T.T.

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?

如何为 5 个数字编码一个简单的整数循环缓冲区?

I'm thinking in C is the most straightforward?

我在想在C中是最直接的吗?

Thanks.

谢谢。

回答by Matthew Flaschen

Have an array, buffer, of 5 integers. Have an index indto the next element. When you add, do

有一个buffer由 5 个整数组成的数组。有ind下一个元素的索引。添加时,请执行

buffer[ind] = value;
ind = (ind + 1) % 5;

回答by Borealid

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

取一个数组 、arr一个索引idx和一个计数器num

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

插入foo,说arr[idx++] = foo; idx %= buffer_len; num++;

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

要将项目读入foo,请说foo = arr[(idx-num)%buffer_len]; num--;

Add boundary checks.

添加边界检查。

回答by James Curran

If the size and data type of your buffer are fixed, a simple array is all you need:

如果缓冲区的大小和数据类型是固定的,则只需要一个简单的数组:

 int buffer[5];

Add to that a couple pointers:

添加几个指针:

 int* start = &buffer[0];
 int* end   = &buffer[4]+1;
 int* input = start;
 int* output = start;

回答by Raju K

int rI =0;
int wI=0;
#define FIFO_SIZE 3
int checkAvail()
{
int avail=0;

if(wI<rI)
    avail= (rI-wI);
else
    avail = (FIFO_SIZE-wI+rI);
return avail;
}

int addFIFO(int *a, int val)
{
if(checkAvail()>0)
{
    a[wI]=val;
    wI++;
    if(wI>FIFO_SIZE)
        wI=0;
}
else
{
    printf("FIFO full");
}
return 0;
}
 int remFIFO(int *a)
 {
 int val;
if((FIFO_SIZE-checkAvail()>0))
{
    val =a[rI];
    rI++;
    if(rI>FIFO_SIZE)
        rI=0;
}
else
{
    printf("FIFO empty");
}
return 0;
}
int main(array<System::String ^> ^args)
{
int FIFO_ARRAY[FIFO_SIZE]={};
addFIFO(FIFO_ARRAY,1);
addFIFO(FIFO_ARRAY,2);
addFIFO(FIFO_ARRAY,3);
addFIFO(FIFO_ARRAY,4);
remFIFO(FIFO_ARRAY);
remFIFO(FIFO_ARRAY);
remFIFO(FIFO_ARRAY);
remFIFO(FIFO_ARRAY);
remFIFO(FIFO_ARRAY);
}