fork download
  1. #include <string>
  2. #include <iostream>
  3. #include <boost/foreach.hpp>
  4. #include <iterator>
  5.  
  6. template<typename A, typename B>
  7. struct zip_iterator{
  8. typedef typename A::iterator left;
  9. typedef typename B::iterator right;
  10. typedef std::pair<left, right> value_type;
  11. typedef std::forward_iterator_tag iterator_category;
  12. typedef void difference_type;
  13. typedef value_type* pointer;
  14. typedef value_type& reference;
  15.  
  16. value_type it;
  17.  
  18. zip_iterator(){}
  19. zip_iterator(left ai, right bi) : it(ai, bi) {}
  20.  
  21. bool operator == (zip_iterator i) { return it.first == i.it.first && it.second == i.it.second; }
  22. bool operator != (zip_iterator i) { return !(*this == i); }
  23.  
  24. zip_iterator& operator ++ () { it.first++; it.second++; return *this; }
  25. zip_iterator operator ++ (int) { zip_iterator t = *this; ++(*this); return t; }
  26.  
  27. value_type& operator * () { return it; }
  28. value_type* operator -> () { return &it; }
  29. };
  30.  
  31.  
  32. template<typename A, typename B>
  33. struct zip {
  34. A& a;
  35. B& b;
  36.  
  37. zip(A& a, B& b) : a(a), b(b) {}
  38.  
  39. typedef typename A::iterator left;
  40. typedef typename B::iterator right;
  41. typedef std::pair<left, right> value_type;
  42. typedef zip_iterator<A, B> iterator;
  43. typedef zip_iterator<A, B> const_iterator;
  44.  
  45. iterator begin() const { return iterator(a.begin(), b.begin()); }
  46. iterator end() const { return iterator(a.end(), b.end()); }
  47. };
  48.  
  49. typedef zip<std::string, std::string> string_zip;
  50.  
  51. int main()
  52. {
  53. std::string hello( "Hello" );
  54. std::string world( "world" );
  55.  
  56. string_zip zz(hello, world);
  57.  
  58. BOOST_FOREACH( string_zip::value_type val , zz )
  59. {
  60. std::cout << *val.first << *val.second;
  61. }
  62.  
  63. return 0;
  64. }
Success #stdin #stdout 0.01s 2856KB
stdin
Standard input is empty
stdout
Hweolrllod