尝试使用结构在C++中创建循环缓冲区

trying to create a circular buffer in C++ using struct

本文关键字:创建 循环 循环缓冲 缓冲区 C++ 结构      更新时间:2023-10-16

我想使用 c++ 中的结构创建一个循环缓冲区。基本实现。我在将元素插入缓冲区时遇到问题。这是我写的代码。

这是我的结构定义:

#define LENGTH_BUFFER 100
typedef struct {
  int buffer[LENGTH_BUFFER];
  int head;
  int tail;
} ringbuffer;

ringbuffer test;

初始化以将指针设置为 0:

void RingBuffer_Init(ringbuffer temp)
{
  temp.head = 0;
  temp.tail = 0;
}

推送数据功能:

void RingBuffer_Push(int data,ringbuffer temp)
{
  temp.buffer[temp.head] = data;
  temp.head++;
}

这是我调用函数来初始化和推送数据的地方

void main()
{
  RingBuffer_Init(test);
  RingBuffer_Push(25,test);
  cout << test.buffer[0]<<endl;
}

我似乎无法将数据推送到我的缓冲区。 请帮帮我。 它返回所有零。

假设是放置新值的索引,当您推送一个值时temp.head++;必须用temp.head = (temp.head + 1) % BUFFER_LENGTH;替换该值来管理缓冲区的长度。您还必须在缓冲区已满时移动尾巴

我不明白为什么你推 1 个值然后写 5 个值

你说你在C++,那你为什么要用C写?为什么你没有构造函数和Ringbuffer上的push/pop/top操作?

{编辑添加}

正如您要求的一种非常简单的 c++ 方法

#include <iostream>
using namespace std;
#define LENGTH_BUFFER 4
// in c++ we use a struct when all members are public (by default all is public in a struct),
// but this is dangerous because all can be modified from outside without any protection,
// so I prefer to use a class with public/private parts
class RingBuffer {
  public:
    // The constructor, it replaces RingBuffer_Init,
    // The big advantage is you cannot miss to call the constructor
    RingBuffer();
    // it is not needed to have a destructor, the implicit destructor is ok
    // because it is an operation you do not have to give the ringbuffer in parameter
    void push(int data);
    // I had the print operation, it print following the order of insertion
    // to print doesn't change the instance, so I can say the operaiotn is 'const'
    void print() const;
  private:
    int buffer[LENGTH_BUFFER];
    int head; // index of the future value
    int tail; // index of the older inserted value, except if empty / head == index
};
// The buffer is initialized empty, head == tail
// I can initialize the indexes by any other valid
// value, this is not relevant
RingBuffer::RingBuffer() : head(0), tail(0) {
}
// push a new value, 
void RingBuffer::push(int data)
{
  buffer[head] = data;
  head = (head + 1) % LENGTH_BUFFER;
  if (head == tail)
    tail = (tail + 1) % LENGTH_BUFFER;
}
// print the content and indexes
void RingBuffer::print() const {
  for (int p = tail; p != head; p = (p + 1)  % LENGTH_BUFFER)
    cout << buffer[p] << ' ';
  cout << " (head=" << head << ", tail = " << tail << ')'  << endl;
}
int main()
{
  RingBuffer test;
  test.print();
  test.push(1);
  test.print();
  test.push(2);
  test.print();
  test.push(3);
  test.print();
  test.push(4);
  test.print();
  test.push(5);
  test.push(6);
  test.print();
  return 0;
}

我减小了缓冲区的大小,以使用很少的值进行旋转。

执行产生:

 (head=0, tail = 0)
1  (head=1, tail = 0)
1 2  (head=2, tail = 0)
1 2 3  (head=3, tail = 0)
2 3 4  (head=0, tail = 1)
4 5 6  (head=2, tail = 3)

正如您在该实现中看到的那样,一个条目丢失了,它的大小为 4,但仅管理 3 个值。我让你可以改变它,添加top(),back(),pop()等