什么是在环形缓冲区中向后循环的好方法?

时间:2014-03-05 03:35:23

标签: c++

假设我有一个缓冲区:

static const int BUFFER_SIZE = 3; // for example
int buffer[BUFFER_SIZE];

我想循环它

int index = 0;
for( ;; )
{
    buffer[index] = ...;
    index = (index + 1) % BUFFER_SIZE; // index = 0, 1, 2, 0, 1, 2, 0, 1, 2, ...
}   

但是如果我想向后循环缓冲区会发生什么? 例如:0,2,1,0,2,1,......

现在我这样做:

index  = (index <= 0) ? BUFFER_SIZE - 1 : index  - 1;

有没有更好的方法来进行这些操作?

2 个答案:

答案 0 :(得分:2)

本着第一个决定的精神,我们可以写下:

int idx = 0; 
int i=0;
for (;;) {
      buffer[idx] = ...;
      i =  (i+1) % BUFFER_SIZE;
      idx = (BUFFER_SIZE - i) % BUFFER_SIZE;
}

答案 1 :(得分:1)

你可以试试这个:

for (int *p = buffer;;) {
  if (p == buffer) p = buffer + BUFFER_SIZE;        

  // these next lines could be combined using the pre-decrement operator
  // at expense of some readability
  p--;
  int index = int(p - buffer); // in case you need the zero-based index
  *p = ...;   
}

或者这个:

for (int *p = buffer + BUFFER_SIZE - 1;;p--) {
  int index = int(p - buffer); // in case you need the zero-based index
  *p = ...;
  if (p == buffer) p = buffer + BUFFER_SIZE;        
}