1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
// This is C++11 code!
#include <iterator>
#include <utility>
template <typename Iterator1, typename Iterator2>
struct zip_iterator_t
{
Iterator1 first, end1;
Iterator2 second, end2;
zip_iterator_t() { }
zip_iterator_t(
Iterator1 begin1, Iterator1 end1,
Iterator2 begin2, Iterator2 end2
):
first ( begin1 ), end1( end1 ),
second( begin2 ), end2( end2 )
{ }
zip_iterator_t& operator ++ ()
{
if (first != end1) ++first;
if (second != end2) ++second;
return *this;
}
zip_iterator_t operator ++ (int) const
{
zip_iterator_t result( *this );
operator ++ ();
return result;
}
bool ok() const { return (first != end1) && (second != end2); }
bool operator == ( const zip_iterator_t& that ) const
{
return ok() == that.ok();
}
bool operator != ( const zip_iterator_t& that ) const
{
return ok() != that.ok();
}
typedef std::pair <
typename std::iterator_traits <Iterator1> ::value_type,
typename std::iterator_traits <Iterator2> ::value_type> value_type;
value_type operator * () const
{
return std::make_pair( *first, *second );
}
zip_iterator_t begin() const { return *this; }
zip_iterator_t end() const { return zip_iterator_t(); }
};
template <typename Iterator1, typename Iterator2> inline
struct zip_iterator_t <Iterator1, Iterator2>
zip_iterator(
Iterator1 begin1, Iterator1 end1,
Iterator2 begin2, Iterator2 end2
) {
return zip_iterator_t <Iterator1, Iterator2> ( begin1, end1, begin2, end2 );
}
template <template <typename...> class Container, typename T>
Container <std::pair <T, T>>
zip( const Container <T> & a, const Container <T> & b )
{
Container <std::pair <T, T>> result;
for (auto zi : zip_iterator( a.begin(), a.end(), b.begin(), b.end() ))
{
result.push_back( zi );
}
return result;
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <string> boys( { "Aaron", "Basil", "Cedric", "Derrik", "Edward", "Ferris", "Gordon" } );
vector <string> girls( { "Alanna", "Brittany", "Cara", "D'Lynn", "Erin", "Farrah" } );
typedef pair <string, string> couple_t;
vector <couple_t> couples = zip( boys, girls );
for (auto couple: couples)
{
cout << couple.first << " and " << couple.second
<< ", sitting in a tree, K-I-S-S-I-N-G.\n";
}
cout << "Poor Gordon!\n";
return 0;
}
|