我想使用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;
}
我似乎无法将数据推送到缓冲区。请帮帮我。它返回所有零。
答案 0 :(得分:0)
假设 head 是放置新值的索引,当您推入值temp.head++;
时必须用temp.head = (temp.head + 1) % BUFFER_LENGTH;
代替,以管理缓冲区的长度。当缓冲区已满时,还必须移动 tail 。
我不明白为什么要先推1个值然后写5个值
您说您使用C ++,那么为什么要用C编写?为什么在环形缓冲区上没有构造函数和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()等