#include <stdlib.h>
#include <iostream>
#include <assert.h>
template<int Capcity>
class cbuffer
{
public:
cbuffer() : sz(0), p(0){}
void push_back(int n)
{
buf[p++] = n;
if (sz < Capcity)
sz++;
if (p >= Capcity)
p = 0;
}
int size() const
{
return sz;
}
int operator[](int n) const
{
assert(n < sz);
n = p - sz + n;
if (n < 0)
n += Capcity;
return buf[n];
}
int buf[Capcity];
int sz, p;
};
int main()
{
cbuffer<5> buf;
// insert random 100 numbers
for (int i = 0; i < 100; ++i)
buf.push_back(rand());
// output to cout contents of the circular buffer
for (int i = 0; i < buf.size(); ++i)
std::cout << buf[i] << ' ';
}
I2luY2x1ZGUgPHN0ZGxpYi5oPgojaW5jbHVkZSA8aW9zdHJlYW0+CiNpbmNsdWRlIDxhc3NlcnQuaD4KCnRlbXBsYXRlPGludCBDYXBjaXR5PgpjbGFzcyBjYnVmZmVyCnsKcHVibGljOgogICAgY2J1ZmZlcigpIDogc3ooMCksIHAoMCl7fQogICAgdm9pZCBwdXNoX2JhY2soaW50IG4pCiAgICB7CiAgICAgICAgYnVmW3ArK10gPSBuOwogICAgICAgIGlmIChzeiA8IENhcGNpdHkpCiAgICAgICAgICAgIHN6Kys7CiAgICAgICAgaWYgKHAgPj0gQ2FwY2l0eSkKICAgICAgICAgICAgcCA9IDA7CiAgICB9CiAgICBpbnQgc2l6ZSgpIGNvbnN0CiAgICB7CiAgICAgICAgcmV0dXJuIHN6OwogICAgfQogICAgaW50IG9wZXJhdG9yW10oaW50IG4pIGNvbnN0CiAgICB7CiAgICAgICAgYXNzZXJ0KG4gPCBzeik7CiAgICAgICAgbiA9IHAgLSBzeiArIG47CiAgICAgICAgaWYgKG4gPCAwKQogICAgICAgICAgICBuICs9IENhcGNpdHk7CiAgICAgICAgcmV0dXJuIGJ1ZltuXTsKICAgIH0KICAgIGludCBidWZbQ2FwY2l0eV07CiAgICBpbnQgc3osIHA7Cn07CgppbnQgbWFpbigpCnsKICAgIGNidWZmZXI8NT4gYnVmOwoKICAgIC8vIGluc2VydCByYW5kb20gMTAwIG51bWJlcnMKICAgIGZvciAoaW50IGkgPSAwOyBpIDwgMTAwOyArK2kpCiAgICAgICAgYnVmLnB1c2hfYmFjayhyYW5kKCkpOwoKICAgIC8vIG91dHB1dCB0byBjb3V0IGNvbnRlbnRzIG9mIHRoZSBjaXJjdWxhciBidWZmZXIKICAgIGZvciAoaW50IGkgPSAwOyBpIDwgYnVmLnNpemUoKTsgKytpKQogICAgICAgIHN0ZDo6Y291dCA8PCBidWZbaV0gPDwgJyAnOwp9Cg==