merge_arrays.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // Copyright Keld Helsgaun 2000, Oliver Kowalke 2014.
  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 <cstdlib>
  7. #include <cstddef>
  8. #include <iostream>
  9. #include <vector>
  10. #include <boost/bind.hpp>
  11. #include <boost/foreach.hpp>
  12. typedef boost::coroutines::symmetric_coroutine< void > coro_t;
  13. class merger
  14. {
  15. private:
  16. std::size_t max_;
  17. std::vector< int > & to_;
  18. void run_( coro_t::yield_type & yield)
  19. {
  20. while ( idx < from.size() )
  21. {
  22. if ( other->from[other->idx] < from[idx])
  23. yield( other->coro);
  24. to_.push_back(from[idx++]);
  25. }
  26. while ( to_.size() < max_)
  27. to_.push_back( other->from[other->idx++]);
  28. }
  29. merger( merger const&);
  30. merger & operator=( merger const&);
  31. public:
  32. std::vector< int > const& from;
  33. std::size_t idx;
  34. merger * other;
  35. coro_t::call_type coro;
  36. merger( std::vector< int > const& from_, std::vector< int > & to, std::size_t max) :
  37. max_( max),
  38. to_( to),
  39. from( from_),
  40. idx( 0),
  41. other( 0),
  42. coro( boost::bind( & merger::run_, this, _1) )
  43. {}
  44. void run()
  45. { coro(); }
  46. };
  47. std::vector< int > merge( std::vector< int > const& a, std::vector< int > const& b)
  48. {
  49. std::vector< int > c;
  50. merger ma( a, c, a.size() + b. size() );
  51. merger mb( b, c, a.size() + b. size() );
  52. ma.other = & mb;
  53. mb.other = & ma;
  54. ma.run();
  55. return c;
  56. }
  57. void print( std::string const& name, std::vector< int > const& v)
  58. {
  59. std::cout << name << " : ";
  60. BOOST_FOREACH( int itm, v)
  61. { std::cout << itm << " "; }
  62. std::cout << "\n";
  63. }
  64. int main( int argc, char * argv[])
  65. {
  66. std::vector< int > a;
  67. a.push_back( 1);
  68. a.push_back( 5);
  69. a.push_back( 6);
  70. a.push_back( 10);
  71. print( "a", a);
  72. std::vector< int > b;
  73. b.push_back( 2);
  74. b.push_back( 4);
  75. b.push_back( 7);
  76. b.push_back( 8);
  77. b.push_back( 9);
  78. b.push_back( 13);
  79. print( "b", b);
  80. std::vector< int > c = merge( a, b);
  81. print( "c", c);
  82. std::cout << "Done" << std::endl;
  83. return EXIT_SUCCESS;
  84. }