layout.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright Nat Goodspeed 2013.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #include <boost/coroutine/all.hpp>
  6. #include <iostream>
  7. #include <iomanip>
  8. #include <vector>
  9. #include <string>
  10. #include <utility>
  11. #include <boost/assign/list_of.hpp>
  12. #include <boost/bind.hpp>
  13. #include <boost/range.hpp>
  14. struct FinalEOL
  15. {
  16. ~FinalEOL() { std::cout << std::endl; }
  17. };
  18. void layout(boost::coroutines::asymmetric_coroutine<std::string>::pull_type& in, int num, int width)
  19. {
  20. // Finish the last line when we leave by whatever means
  21. FinalEOL eol;
  22. // Pull values from upstream, lay them out 'num' to a line
  23. for (;;)
  24. {
  25. for (int i = 0; i < num; ++i)
  26. {
  27. // when we exhaust the input, stop
  28. if (! in)
  29. return;
  30. std::cout << std::setw(width) << in.get();
  31. // now that we've handled this item, advance to next
  32. in();
  33. }
  34. // after 'num' items, line break
  35. std::cout << std::endl;
  36. }
  37. }
  38. int main(int argc, char *argv[])
  39. {
  40. std::vector<std::string> words = boost::assign::list_of
  41. ("peas")
  42. ("porridge")
  43. ("hot")
  44. ("peas")
  45. ("porridge")
  46. ("cold")
  47. ("peas")
  48. ("porridge")
  49. ("in")
  50. ("the")
  51. ("pot")
  52. ("nine")
  53. ("days")
  54. ("old")
  55. ;
  56. boost::coroutines::asymmetric_coroutine<std::string>::push_type writer(
  57. boost::bind(layout, _1, 5, 15));
  58. std::copy(boost::begin(words), boost::end(words), boost::begin(writer));
  59. std::cout << "\nDone" << std::endl;
  60. return EXIT_SUCCESS;
  61. }