If you can use Boost try boost :: circle_buffer :

This is a kind of sequence similar to std::list or std::deque . It supports random access iterators, insert and delete constant time operations at the beginning or at the end of the buffer, and compatibility with std algorithms.
It provides storage with a fixed capacity: when the buffer is full, new data is written, starting from the beginning of the buffer and overwriting the old
// Create a circular buffer with a capacity for 5 integers. boost::circular_buffer<int> cb(5); // Insert elements into the buffer. cb.push_back(3); cb.push_back(24); cb.push_back(51); cb.push_back(62); cb.push_back(37); int a = cb[0]; // a == 3 int b = cb[1]; // b == 24 int c = cb[2]; // c == 51 // The buffer is full now, so pushing subsequent // elements will overwrite the front-most elements. cb.push_back(8); // overwrite 3 with 8 cb.push_back(12); // overwrite 24 with 12 // The buffer now contains 51, 62, 37, 8, 12. // Elements can be popped from either the front or the back. cb.pop_back(); // 12 is removed cb.pop_front(); // 51 is removed
circular_buffer stores its elements in an adjacent memory area, which allows you to quickly insert, delete and randomly access elements <<time> .
PS ... or add a circular buffer directly as suggested by Taemyr .
Overload Magazine # 50 - August 2002 has a nice introduction (by Pete Goodliff) for writing a robust STL ring buffer.
manlio May 18 '17 at 8:37 2017-05-18 08:37
source share