transform_iterator_example.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. #include <functional>
  6. #include <algorithm>
  7. #include <iostream>
  8. #include <boost/iterator/transform_iterator.hpp>
  9. // What a bummer. We can't use std::binder1st with transform iterator
  10. // because it does not have a default constructor. Here's a version
  11. // that does.
  12. namespace boost {
  13. template <class Operation>
  14. class binder1st {
  15. public:
  16. typedef typename Operation::result_type result_type;
  17. typedef typename Operation::second_argument_type argument_type;
  18. protected:
  19. Operation op;
  20. typename Operation::first_argument_type value;
  21. public:
  22. binder1st() { } // this had to be added!
  23. binder1st(const Operation& x,
  24. const typename Operation::first_argument_type& y)
  25. : op(x), value(y) {}
  26. typename Operation::result_type
  27. operator()(const typename Operation::second_argument_type& x) const {
  28. return op(value, x);
  29. }
  30. };
  31. template <class Operation, class T>
  32. inline binder1st<Operation> bind1st(const Operation& op, const T& x) {
  33. typedef typename Operation::first_argument_type arg1_type;
  34. return binder1st<Operation>(op, arg1_type(x));
  35. }
  36. } // namespace boost
  37. int
  38. main(int, char*[])
  39. {
  40. // This is a simple example of using the transform_iterators class to
  41. // generate iterators that multiply the value returned by dereferencing
  42. // the iterator. In this case we are multiplying by 2.
  43. // Would be cooler to use lambda library in this example.
  44. int x[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
  45. const int N = sizeof(x)/sizeof(int);
  46. typedef boost::binder1st< std::multiplies<int> > Function;
  47. typedef boost::transform_iterator<Function, int*> doubling_iterator;
  48. doubling_iterator i(x, boost::bind1st(std::multiplies<int>(), 2)),
  49. i_end(x + N, boost::bind1st(std::multiplies<int>(), 2));
  50. std::cout << "multiplying the array by 2:" << std::endl;
  51. while (i != i_end)
  52. std::cout << *i++ << " ";
  53. std::cout << std::endl;
  54. std::cout << "adding 4 to each element in the array:" << std::endl;
  55. std::copy(boost::make_transform_iterator(x, boost::bind1st(std::plus<int>(), 4)),
  56. boost::make_transform_iterator(x + N, boost::bind1st(std::plus<int>(), 4)),
  57. std::ostream_iterator<int>(std::cout, " "));
  58. std::cout << std::endl;
  59. return 0;
  60. }