transform_iterator_eg.rst 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. .. Copyright David Abrahams 2006. Distributed under the Boost
  2. .. Software License, Version 1.0. (See accompanying
  3. .. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. Example
  5. .......
  6. This is a simple example of using the transform_iterators class to
  7. generate iterators that multiply (or add to) the value returned by
  8. dereferencing the iterator. It would be cooler to use lambda library
  9. in this example.
  10. ::
  11. int x[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
  12. const int N = sizeof(x)/sizeof(int);
  13. typedef boost::binder1st< std::multiplies<int> > Function;
  14. typedef boost::transform_iterator<Function, int*> doubling_iterator;
  15. doubling_iterator i(x, boost::bind1st(std::multiplies<int>(), 2)),
  16. i_end(x + N, boost::bind1st(std::multiplies<int>(), 2));
  17. std::cout << "multiplying the array by 2:" << std::endl;
  18. while (i != i_end)
  19. std::cout << *i++ << " ";
  20. std::cout << std::endl;
  21. std::cout << "adding 4 to each element in the array:" << std::endl;
  22. std::copy(boost::make_transform_iterator(x, boost::bind1st(std::plus<int>(), 4)),
  23. boost::make_transform_iterator(x + N, boost::bind1st(std::plus<int>(), 4)),
  24. std::ostream_iterator<int>(std::cout, " "));
  25. std::cout << std::endl;
  26. The output is::
  27. multiplying the array by 2:
  28. 2 4 6 8 10 12 14 16
  29. adding 4 to each element in the array:
  30. 5 6 7 8 9 10 11 12
  31. The source code for this example can be found `here`__.
  32. __ ../example/transform_iterator_example.cpp