filter_iterator_example.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // (C) Copyright Jeremy Siek 1999-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 <functional>
  8. #include <iostream>
  9. #include <boost/iterator/filter_iterator.hpp>
  10. #include <boost/cstdlib.hpp> // for exit_success
  11. struct is_positive_number {
  12. bool operator()(int x) { return 0 < x; }
  13. };
  14. int main()
  15. {
  16. int numbers_[] = { 0, -1, 4, -3, 5, 8, -2 };
  17. const int N = sizeof(numbers_)/sizeof(int);
  18. typedef int* base_iterator;
  19. base_iterator numbers(numbers_);
  20. // Example using make_filter_iterator()
  21. std::copy(boost::make_filter_iterator<is_positive_number>(numbers, numbers + N),
  22. boost::make_filter_iterator<is_positive_number>(numbers + N, numbers + N),
  23. std::ostream_iterator<int>(std::cout, " "));
  24. std::cout << std::endl;
  25. // Example using filter_iterator
  26. typedef boost::filter_iterator<is_positive_number, base_iterator>
  27. FilterIter;
  28. is_positive_number predicate;
  29. FilterIter filter_iter_first(predicate, numbers, numbers + N);
  30. FilterIter filter_iter_last(predicate, numbers + N, numbers + N);
  31. std::copy(filter_iter_first, filter_iter_last, std::ostream_iterator<int>(std::cout, " "));
  32. std::cout << std::endl;
  33. // Another example using make_filter_iterator()
  34. std::copy(
  35. boost::make_filter_iterator(
  36. std::bind2nd(std::greater<int>(), -2)
  37. , numbers, numbers + N)
  38. , boost::make_filter_iterator(
  39. std::bind2nd(std::greater<int>(), -2)
  40. , numbers + N, numbers + N)
  41. , std::ostream_iterator<int>(std::cout, " ")
  42. );
  43. std::cout << std::endl;
  44. return boost::exit_success;
  45. }