PageRenderTime 43ms CodeModel.GetById 32ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/Src/Dependencies/Boost/libs/iterator/example/transform_iterator_example.cpp

http://hadesmem.googlecode.com/
C++ | 76 lines | 48 code | 17 blank | 11 comment | 2 complexity | 2635f96c73c0528a84cd716195f07a30 MD5 | raw file
 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
16namespace boost {
17
18  template <class Operation> 
19  class binder1st
20    : public std::unary_function<typename Operation::second_argument_type,
21                                 typename Operation::result_type> {
22  protected:
23    Operation op;
24    typename Operation::first_argument_type value;
25  public:
26    binder1st() { } // this had to be added!
27    binder1st(const Operation& x,
28              const typename Operation::first_argument_type& y)
29        : op(x), value(y) {}
30    typename Operation::result_type
31    operator()(const typename Operation::second_argument_type& x) const {
32      return op(value, x); 
33    }
34  };
35
36  template <class Operation, class T>
37  inline binder1st<Operation> bind1st(const Operation& op, const T& x) {
38    typedef typename Operation::first_argument_type arg1_type;
39    return binder1st<Operation>(op, arg1_type(x));
40  }
41
42} // namespace boost
43
44int
45main(int, char*[])
46{
47  // This is a simple example of using the transform_iterators class to
48  // generate iterators that multiply the value returned by dereferencing
49  // the iterator. In this case we are multiplying by 2.
50  // Would be cooler to use lambda library in this example.
51
52  int x[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
53  const int N = sizeof(x)/sizeof(int);
54
55  typedef boost::binder1st< std::multiplies<int> > Function;
56  typedef boost::transform_iterator<Function, int*> doubling_iterator;
57
58  doubling_iterator i(x, boost::bind1st(std::multiplies<int>(), 2)),
59    i_end(x + N, boost::bind1st(std::multiplies<int>(), 2));
60
61  std::cout << "multiplying the array by 2:" << std::endl;
62  while (i != i_end)
63    std::cout << *i++ << " ";
64  std::cout << std::endl;
65
66  std::cout << "adding 4 to each element in the array:" << std::endl;
67
68  std::copy(boost::make_transform_iterator(x, boost::bind1st(std::plus<int>(), 4)),
69            boost::make_transform_iterator(x + N, boost::bind1st(std::plus<int>(), 4)),
70            std::ostream_iterator<int>(std::cout, " "));
71  std::cout << std::endl;
72  
73  return 0;
74}
75
76