filter_iterator_eg.rst 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 uses ``filter_iterator`` and then
  7. ``make_filter_iterator`` to output only the positive integers from an
  8. array of integers. Then ``make_filter_iterator`` is is used to output
  9. the integers greater than ``-2``.
  10. ::
  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 filter_iterator
  21. typedef boost::filter_iterator<is_positive_number, base_iterator>
  22. FilterIter;
  23. is_positive_number predicate;
  24. FilterIter filter_iter_first(predicate, numbers, numbers + N);
  25. FilterIter filter_iter_last(predicate, numbers + N, numbers + N);
  26. std::copy(filter_iter_first, filter_iter_last, std::ostream_iterator<int>(std::cout, " "));
  27. std::cout << std::endl;
  28. // Example using make_filter_iterator()
  29. std::copy(boost::make_filter_iterator<is_positive_number>(numbers, numbers + N),
  30. boost::make_filter_iterator<is_positive_number>(numbers + N, numbers + N),
  31. 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. }
  46. The output is::
  47. 4 5 8
  48. 4 5 8
  49. 0 -1 4 5 8
  50. The source code for this example can be found `here`__.
  51. __ ../example/filter_iterator_example.cpp