indirect_iterator_example.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 <boost/config.hpp>
  6. #include <vector>
  7. #include <iostream>
  8. #include <iterator>
  9. #include <functional>
  10. #include <algorithm>
  11. #include <boost/iterator/indirect_iterator.hpp>
  12. int main(int, char*[])
  13. {
  14. char characters[] = "abcdefg";
  15. const int N = sizeof(characters)/sizeof(char) - 1; // -1 since characters has a null char
  16. char* pointers_to_chars[N]; // at the end.
  17. for (int i = 0; i < N; ++i)
  18. pointers_to_chars[i] = &characters[i];
  19. // Example of using indirect_iterator
  20. boost::indirect_iterator<char**, char>
  21. indirect_first(pointers_to_chars), indirect_last(pointers_to_chars + N);
  22. std::copy(indirect_first, indirect_last, std::ostream_iterator<char>(std::cout, ","));
  23. std::cout << std::endl;
  24. // Example of making mutable and constant indirect iterators
  25. char mutable_characters[N];
  26. char* pointers_to_mutable_chars[N];
  27. for (int j = 0; j < N; ++j)
  28. pointers_to_mutable_chars[j] = &mutable_characters[j];
  29. boost::indirect_iterator<char* const*> mutable_indirect_first(pointers_to_mutable_chars),
  30. mutable_indirect_last(pointers_to_mutable_chars + N);
  31. boost::indirect_iterator<char* const*, char const> const_indirect_first(pointers_to_chars),
  32. const_indirect_last(pointers_to_chars + N);
  33. std::transform(const_indirect_first, const_indirect_last,
  34. mutable_indirect_first, std::bind1st(std::plus<char>(), 1));
  35. std::copy(mutable_indirect_first, mutable_indirect_last,
  36. std::ostream_iterator<char>(std::cout, ","));
  37. std::cout << std::endl;
  38. // Example of using make_indirect_iterator()
  39. std::copy(boost::make_indirect_iterator(pointers_to_chars),
  40. boost::make_indirect_iterator(pointers_to_chars + N),
  41. std::ostream_iterator<char>(std::cout, ","));
  42. std::cout << std::endl;
  43. return 0;
  44. }