fork download
  1. #include <stdlib.h>
  2. #include <iostream>
  3. #include <assert.h>
  4.  
  5. template<int Capcity>
  6. class cbuffer
  7. {
  8. public:
  9. cbuffer() : sz(0), p(0){}
  10. void push_back(int n)
  11. {
  12. buf[p++] = n;
  13. if (sz < Capcity)
  14. sz++;
  15. if (p >= Capcity)
  16. p = 0;
  17. }
  18. int size() const
  19. {
  20. return sz;
  21. }
  22. int operator[](int n) const
  23. {
  24. assert(n < sz);
  25. n = p - sz + n;
  26. if (n < 0)
  27. n += Capcity;
  28. return buf[n];
  29. }
  30. int buf[Capcity];
  31. int sz, p;
  32. };
  33.  
  34. int main()
  35. {
  36. cbuffer<5> buf;
  37.  
  38. // insert random 100 numbers
  39. for (int i = 0; i < 100; ++i)
  40. buf.push_back(rand());
  41.  
  42. // output to cout contents of the circular buffer
  43. for (int i = 0; i < buf.size(); ++i)
  44. std::cout << buf[i] << ' ';
  45. }
  46.  
Success #stdin #stdout 0s 15224KB
stdin
Standard input is empty
stdout
1984210012 855636226 1749698586 1469348094 1956297539