circular_buffer

时间:2023-03-08 22:32:11

编程有时需要使用定长的容器(fixed size container)。实现旋转容器可以像下面这样:

std::vector<T> vec(size);
vec[i % size] = newelem;

但boost的circular_buffer提供更多功能,我们不需要重复造*了(DRY):

#include <boost/circular_buffer.hpp>

    boost::circular_buffer<int> cb();

    // Insert threee elements into the buffer.
cb.push_back();
std::cout << "1 inserted, size:" << cb.size() << endl;
std::cout << "latest is " << cb[cb.size() - ] << endl; cb.push_back();
std::cout << "2 inserted, size:" << cb.size() << endl;
std::cout << "latest is " << cb[cb.size()-] << endl; cb.push_back();
std::cout << "3 inserted, size:" << cb.size() << endl;
std::cout << "latest is " << cb[cb.size()-] << endl; int a = cb[]; // a == 1
int b = cb[]; // b == 2
int c = cb[]; // c == 3 std::cout << "1st is" << a << endl;
std::cout << "2nd is" << b << endl; // The buffer is full now, so pushing subsequent
// elements will overwrite the front-most elements. cb.push_back(); // Overwrite 1 with 4.
std::cout << "4 inserted, size:" << cb.size() << endl;
std::cout << "latest is " << cb[cb.size()-] << endl; cb.push_back(); // Overwrite 2 with 5.
std::cout << "5 inserted, size:" << cb.size() << endl;
std::cout << "latest is " << cb[cb.size()-] << endl; // The buffer now contains 3, 4 and 5.
a = cb[]; // a == 3
b = cb[]; // b == 4
c = cb[]; // c == 5
std::cout << "1st is" << a << endl; cb.pop_back(); // 5 is removed.
cb.pop_front(); // 3 is removed.
std::cout << "head and tail removed, size:" << cb.size() << endl;
std::cout << "latest is " << cb[cb.size() - ] << endl;
// Leaving only one element with value = 4.
int d = cb[]; // d == 4