This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Lazy zipper

By: a guest on May 16th, 2012  |  syntax: C++  |  size: 1.27 KB  |  views: 53  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
This paste has a previous version, view the difference. Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <iostream>
  2. #include <vector>
  3. #include <tuple>
  4.  
  5. template <class T, class Y>
  6. class zipper {
  7.         class iterator {
  8.         public:
  9.                 iterator(typename T::iterator tIt, typename Y::iterator yIt) : tIt(tIt), yIt(yIt) {}
  10.                 bool operator==(const iterator &i) {
  11.                         return (tIt==i.tIt || yIt==i.yIt);
  12.                 }
  13.                 std::tuple<typename T::value_type&, typename Y::value_type&> operator*() {
  14.                         return std::forward_as_tuple(*tIt, *yIt);
  15.                 }
  16.                 iterator& operator++() {
  17.                         ++tIt;
  18.                         ++yIt;
  19.                         return *this;
  20.                 }
  21.                 iterator operator++(int) {
  22.                         iterator tmp = *this;
  23.                         ++*this;
  24.                         return tmp;
  25.                 }
  26.                 bool operator!=(const iterator &i) {
  27.                         return (tIt!=i.tIt && yIt!=i.yIt);
  28.                 }
  29.         private:
  30.                 typename T::iterator tIt;
  31.                 typename Y::iterator yIt;
  32.         };
  33.         T& t;
  34.         Y& y;
  35. public:
  36.         zipper(T& t, Y& y) : t(t), y(y) {}
  37.         iterator begin() { return iterator(t.begin(), y.begin()); }
  38.         iterator end() { return iterator(t.end(), y.end()); }
  39. };
  40.  
  41. template<class T, class Y>
  42. zipper<T,Y> zip(T& t, Y& y) { return zipper<T,Y>(t, y); }
  43.  
  44. using namespace std;
  45.  
  46. int main() {
  47.         vector<int> v{0,1,2};
  48.         vector<string> u{"five","four","three","two","one"};
  49.         for ( auto x : zip(u,v) ) {
  50.                 cout << get<0>(x) << "\t" << get<1>(x) << endl;
  51.         }
  52. }
  53.  
  54. /* Output:
  55.  * "five    0"
  56.  * "four    1"
  57.  * "three   2"
  58.  */
clone this paste RAW Paste Data