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