1. 简介
虽然STL中有queue和deque,但是他们是无限扩展大小的,如果想限定一个定量缓冲,就必须不停的pop操作,而且queue没有随机访问的操作。如果想要维护一个定长缓冲区,我们可以考虑使用Boost的circular_buffer,它既可以满足定长的需求,也支持随机存取,而且头部和尾部可以插入 。
boost::circular_buffer维护了一块连续内存块作为缓存区,当缓存区内的数据存满时,继续存入数据就覆盖掉旧的数据。
2. 说明
boost::circular_buffer cb(3);
cb.size();
cb.capacity();
cb.empty();
cb.full();
cb.push_back(4);
cb.push_front(5);
cb.pop_back();
cb.pop_front();
cb[0];
cb.at(0);
cb.front();
cb.back();
3. 代码示例
#include<iostream>
using namespace std;
#include<boost/circular_buffer.hpp>
int main()
{
boost::circular_buffer cb(3);
cb.push_back(1);
cb.push_back(2);
cb.push_back(3);
for (int i = 0; i < cb.size(); ++i) cout << cb[i] << " ";
cout << endl;
cb.push_back(4);
for (int i = 0; i < cb.size(); ++i) cout << cb[i] << " ";
cout << endl;
cb.push_front(5);
for (int i = 0; i < cb.size(); ++i) cout << cb[i] << " ";
cout << endl;
cb.pop_back();
for (int i = 0; i < cb.size(); ++i) cout << cb[i] << " ";
cout << endl;
cb.pop_front();
for (int i = 0; i < cb.size(); ++i) cout << cb[i] << " ";
cout << endl;
return 0;
}
输出:
1 2 3
2 3 4
5 2 3
5 2
2
参考:https://www.boost.org/doc/libs/1_77_0/doc/html/boost/circular_buffer.html
|