boost的circular_buffer
如果我们要缓存过去固定天数的记录时,一种方法是使用std::deque
,但这样当新记录出来后,还需要判断队列长度,必要时还需要手工pop
老记录。boost的circular_buffer提供自动的方法来实现该操作,利用连续内存,以环形的方式保存记录,因此效率极高。
boost::circular_buffer
支持:
std::deque
操作,包括push_back
,push_front
,pop_back
,pop_front
,front
,back
等操作。所有操作复杂性都是$O(1)$。- 随机存取!和
vector
一样,支持下标[i]
以及at(i)
,且存取时间为$O(1)$。 - 支持
iterator
,因此begin
,end
,for in
用于各种循环。 - 所有
stl
算法可自动适用于circular_buffer
,用法和其它stl
容器一致。
#include <boost/circular_buffer.hpp>
int main() {
// set a curcular_buffer with max capacity of 3
boost::circular_buffer<int> v(3);
// push_back will push the data to the tail
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
// output 2, 3, 4
// circular_buffer supports interator, so can support STL for loop grammer and all STL algorithm
for (auto i : v)
std::cout << i << std::endl;
// we can also use push_front to the front
v.push_font(5);
// output 5, 2, 3
for (auto i = v.begin(); i != v.end(); ++i)
std::cout << *i << std::endl;
// we can change the capacity, the overflow records will be removed
v.set_capacaity(2);
// output 52
std::cout << v.front() << v.end();
// output 5, 2
for (auto i : v)
std::cout << i << std::endl;
// we can treat circula_buffer as a typical deque
v.pop_back();
v.pop_front();
}