circular_buffer_example.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2003-2008 Jan Gaspar.
  2. // Copyright 2013 Paul A. Bristow. Added some Quickbook snippet markers.
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See the accompanying file LICENSE_1_0.txt
  5. // or a copy at <http://www.boost.org/LICENSE_1_0.txt>.)
  6. //[circular_buffer_example_1
  7. /*`For all examples, we need this include:
  8. */
  9. #include <boost/circular_buffer.hpp>
  10. //] [/circular_buffer_example_1]
  11. int main()
  12. {
  13. //[circular_buffer_example_2
  14. // Create a circular buffer with a capacity for 3 integers.
  15. boost::circular_buffer<int> cb(3);
  16. // Insert three elements into the buffer.
  17. cb.push_back(1);
  18. cb.push_back(2);
  19. cb.push_back(3);
  20. int a = cb[0]; // a == 1
  21. int b = cb[1]; // b == 2
  22. int c = cb[2]; // c == 3
  23. // The buffer is full now, so pushing subsequent
  24. // elements will overwrite the front-most elements.
  25. cb.push_back(4); // Overwrite 1 with 4.
  26. cb.push_back(5); // Overwrite 2 with 5.
  27. // The buffer now contains 3, 4 and 5.
  28. a = cb[0]; // a == 3
  29. b = cb[1]; // b == 4
  30. c = cb[2]; // c == 5
  31. // Elements can be popped from either the front or the back.
  32. cb.pop_back(); // 5 is removed.
  33. cb.pop_front(); // 3 is removed.
  34. // Leaving only one element with value = 4.
  35. int d = cb[0]; // d == 4
  36. //] [/circular_buffer_example_2]
  37. return 0;
  38. }
  39. /*
  40. //[circular_buffer_example_output
  41. There is no output from this example.
  42. //] [/circular_buffer_example_output]
  43. */