• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // (C) Copyright Jeremy Siek 2000-2004.
2 // Distributed under the Boost Software License, Version 1.0. (See
3 // accompanying file LICENSE_1_0.txt or copy at
4 // http://www.boost.org/LICENSE_1_0.txt)
5 
6 
7 #include <functional>
8 #include <algorithm>
9 #include <iostream>
10 #include <boost/iterator/transform_iterator.hpp>
11 
12 // What a bummer. We can't use std::binder1st with transform iterator
13 // because it does not have a default constructor. Here's a version
14 // that does.
15 
16 namespace boost {
17 
18   template <class Operation>
19   class binder1st {
20   public:
21     typedef typename Operation::result_type result_type;
22     typedef typename Operation::second_argument_type argument_type;
23   protected:
24     Operation op;
25     typename Operation::first_argument_type value;
26   public:
binder1st()27     binder1st() { } // this had to be added!
binder1st(const Operation & x,const typename Operation::first_argument_type & y)28     binder1st(const Operation& x,
29               const typename Operation::first_argument_type& y)
30         : op(x), value(y) {}
31     typename Operation::result_type
operator ()(const typename Operation::second_argument_type & x) const32     operator()(const typename Operation::second_argument_type& x) const {
33       return op(value, x);
34     }
35   };
36 
37   template <class Operation, class T>
bind1st(const Operation & op,const T & x)38   inline binder1st<Operation> bind1st(const Operation& op, const T& x) {
39     typedef typename Operation::first_argument_type arg1_type;
40     return binder1st<Operation>(op, arg1_type(x));
41   }
42 
43 } // namespace boost
44 
45 int
main(int,char * [])46 main(int, char*[])
47 {
48   // This is a simple example of using the transform_iterators class to
49   // generate iterators that multiply the value returned by dereferencing
50   // the iterator. In this case we are multiplying by 2.
51   // Would be cooler to use lambda library in this example.
52 
53   int x[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
54   const int N = sizeof(x)/sizeof(int);
55 
56   typedef boost::binder1st< std::multiplies<int> > Function;
57   typedef boost::transform_iterator<Function, int*> doubling_iterator;
58 
59   doubling_iterator i(x, boost::bind1st(std::multiplies<int>(), 2)),
60     i_end(x + N, boost::bind1st(std::multiplies<int>(), 2));
61 
62   std::cout << "multiplying the array by 2:" << std::endl;
63   while (i != i_end)
64     std::cout << *i++ << " ";
65   std::cout << std::endl;
66 
67   std::cout << "adding 4 to each element in the array:" << std::endl;
68 
69   std::copy(boost::make_transform_iterator(x, boost::bind1st(std::plus<int>(), 4)),
70             boost::make_transform_iterator(x + N, boost::bind1st(std::plus<int>(), 4)),
71             std::ostream_iterator<int>(std::cout, " "));
72   std::cout << std::endl;
73 
74   return 0;
75 }
76