indirect_iterator_eg.rst 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 example prints an array of characters, using
  7. ``indirect_iterator`` to access the array of characters through an
  8. array of pointers. Next ``indirect_iterator`` is used with the
  9. ``transform`` algorithm to copy the characters (incremented by one) to
  10. another array. A constant indirect iterator is used for the source and
  11. a mutable indirect iterator is used for the destination. The last part
  12. of the example prints the original array of characters, but this time
  13. using the ``make_indirect_iterator`` helper function.
  14. ::
  15. char characters[] = "abcdefg";
  16. const int N = sizeof(characters)/sizeof(char) - 1; // -1 since characters has a null char
  17. char* pointers_to_chars[N]; // at the end.
  18. for (int i = 0; i < N; ++i)
  19. pointers_to_chars[i] = &characters[i];
  20. // Example of using indirect_iterator
  21. boost::indirect_iterator<char**, char>
  22. indirect_first(pointers_to_chars), indirect_last(pointers_to_chars + N);
  23. std::copy(indirect_first, indirect_last, std::ostream_iterator<char>(std::cout, ","));
  24. std::cout << std::endl;
  25. // Example of making mutable and constant indirect iterators
  26. char mutable_characters[N];
  27. char* pointers_to_mutable_chars[N];
  28. for (int j = 0; j < N; ++j)
  29. pointers_to_mutable_chars[j] = &mutable_characters[j];
  30. boost::indirect_iterator<char* const*> mutable_indirect_first(pointers_to_mutable_chars),
  31. mutable_indirect_last(pointers_to_mutable_chars + N);
  32. boost::indirect_iterator<char* const*, char const> const_indirect_first(pointers_to_chars),
  33. const_indirect_last(pointers_to_chars + N);
  34. std::transform(const_indirect_first, const_indirect_last,
  35. mutable_indirect_first, std::bind1st(std::plus<char>(), 1));
  36. std::copy(mutable_indirect_first, mutable_indirect_last,
  37. std::ostream_iterator<char>(std::cout, ","));
  38. std::cout << std::endl;
  39. // Example of using make_indirect_iterator()
  40. std::copy(boost::make_indirect_iterator(pointers_to_chars),
  41. boost::make_indirect_iterator(pointers_to_chars + N),
  42. std::ostream_iterator<char>(std::cout, ","));
  43. std::cout << std::endl;
  44. The output is::
  45. a,b,c,d,e,f,g,
  46. b,c,d,e,f,g,h,
  47. a,b,c,d,e,f,g,
  48. The source code for this example can be found `here`__.
  49. __ ../example/indirect_iterator_example.cpp