您正在寻找循环缓冲区或循环缓冲区。
Boost 有它们:
它们有时大大比例如使用 std::deque 滚动您自己,请参阅 ASIO 的此示例:
更新
我认为 boost::circular_buffer 可能是您/应该想要的/ - 因为它抽象了您通常想要的大多数任务的“如何”。但是,创建自己的适配器类型非常简单:
Live On Coliru
#include <vector>
namespace mylib {
template <typename T, typename Container = std::vector<T> >
struct circular : Container {
using Container::Container;
using Container::operator =;
auto& operator[](int i) const {
// mixed signed/unsigned modulo is undefined
while (i<0) i += Container::size();
return Container::operator[](i % Container::size());
}
auto& operator[](int i) {
while (i<0) i += Container::size();
return Container::operator[](i % Container::size());
}
};
}
#include <iostream>
template <typename Whatever>
void test(Whatever const& data) {
std::cout << data[ 5] << ", "; // would output 15
std::cout << data[ 1] << ", "; // would output 10
std::cout << data[-2] << std::endl; // would output 10
}
#include <string>
#include <deque>
int main() {
test(mylib::circular<int> { 5, 10, 15 });
test(mylib::circular<std::string> { "five", "teen", "fiteen" });
test(mylib::circular<std::string, std::deque<std::string> > { "five", "teen", "fiteen" });
test(mylib::circular<int, std::deque<float> > { 5, 10, 15 });
}
打印:
15, 10, 10
fiteen, teen, teen
fiteen, teen, teen
15, 10, 10