circular_buffer_sum_example.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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_sum_example_1
  7. /*`This example shows several functions, including summing all valid values.
  8. */
  9. #include <boost/circular_buffer.hpp>
  10. #include <numeric>
  11. #include <assert.h>
  12. int main(int /*argc*/, char* /*argv*/[])
  13. {
  14. // Create a circular buffer of capacity 3.
  15. boost::circular_buffer<int> cb(3);
  16. assert(cb.capacity() == 3);
  17. // Check is empty.
  18. assert(cb.size() == 0);
  19. assert(cb.empty());
  20. // Insert some elements into the circular buffer.
  21. cb.push_back(1);
  22. cb.push_back(2);
  23. // Assertions to check push_backs have expected effect.
  24. assert(cb[0] == 1);
  25. assert(cb[1] == 2);
  26. assert(!cb.full());
  27. assert(cb.size() == 2);
  28. assert(cb.capacity() == 3);
  29. // Insert some other elements.
  30. cb.push_back(3);
  31. cb.push_back(4);
  32. // Evaluate the sum of all elements.
  33. int sum = std::accumulate(cb.begin(), cb.end(), 0);
  34. // Assertions to check state.
  35. assert(sum == 9);
  36. assert(cb[0] == 2);
  37. assert(cb[1] == 3);
  38. assert(cb[2] == 4);
  39. assert(*cb.begin() == 2);
  40. assert(cb.front() == 2);
  41. assert(cb.back() == 4);
  42. assert(cb.full());
  43. assert(cb.size() == 3);
  44. assert(cb.capacity() == 3);
  45. return 0;
  46. }
  47. //] [/circular_buffer_sum_example_1]
  48. /*
  49. There is no output from this example.
  50. */