counting_iterator_example.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 <algorithm>
  7. #include <iostream>
  8. #include <iterator>
  9. #include <vector>
  10. #include <boost/iterator/counting_iterator.hpp>
  11. #include <boost/iterator/indirect_iterator.hpp>
  12. #include <boost/cstdlib.hpp>
  13. int main(int, char*[])
  14. {
  15. // Example of using counting_iterator
  16. std::cout << "counting from 0 to 4:" << std::endl;
  17. boost::counting_iterator<int> first(0), last(4);
  18. std::copy(first, last, std::ostream_iterator<int>(std::cout, " "));
  19. std::cout << std::endl;
  20. // Example of using counting iterator to create an array of pointers.
  21. int N = 7;
  22. std::vector<int> numbers;
  23. typedef std::vector<int>::iterator n_iter;
  24. // Fill "numbers" array with [0,N)
  25. std::copy(
  26. boost::counting_iterator<int>(0)
  27. , boost::counting_iterator<int>(N)
  28. , std::back_inserter(numbers));
  29. std::vector<std::vector<int>::iterator> pointers;
  30. // Use counting iterator to fill in the array of pointers.
  31. // causes an ICE with MSVC6
  32. std::copy(boost::make_counting_iterator(numbers.begin()),
  33. boost::make_counting_iterator(numbers.end()),
  34. std::back_inserter(pointers));
  35. // Use indirect iterator to print out numbers by accessing
  36. // them through the array of pointers.
  37. std::cout << "indirectly printing out the numbers from 0 to "
  38. << N << std::endl;
  39. std::copy(boost::make_indirect_iterator(pointers.begin()),
  40. boost::make_indirect_iterator(pointers.end()),
  41. std::ostream_iterator<int>(std::cout, " "));
  42. std::cout << std::endl;
  43. return boost::exit_success;
  44. }