如何告诉 Boost 循环缓冲区的当前 'write position' 以启用访问以前存储的值

How to tell the current 'write position' of a Boost Circular Buffer to enable accessing a previously stored value

我想访问 Boost Circular Buffer 中的一个值,例如,5 个位置 'in the past'。因此,假设我现在正在将值“7”写入先前的整数流:

3、5、6、9、2、8、6

因此我现在有:

7、3、5、6、9、2、8、6

我想要“2”,因为那是过去的 5 个位置。我如何获得它?

也就是说,现在的'write index'是多少?

我想我可能需要使用 boost::circular_buffer<double>::const_iterator 但我不确定。

我认为唯一可行的答案是您自己跟踪索引。根据 Boost 文档,容器似乎具有固定的分配大小并且工作方式类似于堆栈。

与其他容器一样,元素本身并不跟踪它们的键。因此,您可以在外部跟踪位置或键等任何属性。看来您只有常用的 std::vector 类函数可用:size()capacity()at()operator[] 等,包括迭代器职能。

我想你能做的最好的事情就是找到一些方法来跟踪 "keys" 或索引号。由于循环缓冲区简单地循环并重写 "overflow," 上的第一个数组,也许您可​​以使用模函数自己进行计数。

我不确定我是否理解正确,但你对模索引的担心对我来说似乎过于焦虑了。如果你问我,循环缓冲区 抽象 的全部目的是对调用者隐藏索引算法。

如果 Boost 让这个实现细节泄露出去,我会对库设计感到非常失望¹

这是一个简单的演示,似乎就是您想要的:

Live On Coliru

#include <iostream>
#include <boost/circular_buffer.hpp>

int main() {
    boost::circular_buffer<int> cb(10); // [tag:cb-so-fixedsize] obviously

    for (int msg : { 3, 5, 6, 9, 2, 8, 6, 7 }) {
        cb.push_back(msg);
    }

    // should be 2
    std::cout << "t0-5: " << cb[4] << "\n";
    std::cout << "t0-5: " << *std::next(cb.begin(), 4) << "\n";

    // should be 9
    std::cout << "t0-5: " << cb[3] << "\n";
    std::cout << "t0-5: " << *std::next(cb.begin(), 3) << "\n";

    while (!cb.empty()) {
        std::cout << cb.front() << " ";
        cb.pop_front();
    }
}

版画

t0-5: 2
t0-5: 2
t0-5: 9
t0-5: 9
3 5 6 9 2 8 6 7 

¹ 我很清楚名称 "circular" 暗示了实现细节,但是嘿。标准库和类似库中的许多数据结构的名称有点令人困惑