пытаясь создать кольцевой буфер в C ++, используя структуру - PullRequest
0 голосов
/ 27 декабря 2018

Я хочу создать кольцевой буфер, используя структуры в 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;
}

Кажется, я не могу отправить данные в свой буфер.пожалуйста, помогите мне.он возвращает все нули.

1 Ответ

0 голосов
/ 27 декабря 2018

предположим, head - это индекс, в который вы помещаете новое значение, когда вы нажимаете значение, temp.head++; должно быть заменено на temp.head = (temp.head + 1) % BUFFER_LENGTH; для управления длиной буфера.Вы также должны переместить хвост , когда буфер заполнен.

Я не понимаю, почему вы нажимаете 1 значение, а затем пишете 5 значений

Вы говорите, что находитесь в C ++так почему ты пишешь на С?почему у вас нет конструктора и операции push / pop / top для кольцевого буфера?

{edit add}

Как вы просили, очень простой способ сделать это в 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 () и т. Д.

...