如何有效地包装固定大小的循环缓冲区的索引 [英] How to efficiently wrap the index of a fixed-size circular buffer

查看:107
本文介绍了如何有效地包装固定大小的循环缓冲区的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个固定大小的循环缓冲区(实现为数组):初始化后,缓冲区将填充有指定的最大元素数量,这允许使用单个位置索引来跟踪我们当前的位置圆圈.

I have a fixed size circular buffer (implemented as an array): upon initialization, the buffer gets filled with the specified maximum number of elements which allows the use of a single position index in order to keep track of our current position in the circle.

访问循环缓冲区中的元素的有效方法是什么?这是我当前的解决方案:

What is an efficient way to access an element in the circular buffer? Here is my current solution:

int GetElement(int index)
{
    if (index >= buffer_size || index < 0)
    {
        // some code to handle the case
    }
    else
    {
        // wrap the index
        index = end_index + index >= buffer_size ? (index + end_index) - buffer_size : end_index + index;
    }

    return buffer[index];
}

一些定义:
end_index是紧接在圆中最后一个元素之后的元素的索引(也将被视为与start_index或圆的第一个元素相同).
buffer_size是缓冲区的最大大小.

Some definitions:
end_index is the index of the element immediately after the last element in the circle (it would also be considered the same as the start_index, or the first element of the circle).
buffer_size is the maximum size of the buffer.

推荐答案

确保缓冲区始终是两个long的幂并屏蔽掉最高位.

Ensure that the buffer is always a power of two long and mask out the top bits.

这篇关于如何有效地包装固定大小的循环缓冲区的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆