for_each.cpp 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Boost.Range library
  2. //
  3. // Copyright Neil Groves 2009. Use, modification and
  4. // distribution is subject to the Boost Software License, Version
  5. // 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. //
  8. //
  9. // For more information, see http://www.boost.org/libs/range/
  10. //
  11. #include <boost/range/algorithm/for_each.hpp>
  12. #include <boost/test/test_tools.hpp>
  13. #include <boost/test/unit_test.hpp>
  14. #include <boost/array.hpp>
  15. #include <boost/assign.hpp>
  16. #include <boost/range/algorithm.hpp>
  17. #include <list>
  18. #include <set>
  19. #include <vector>
  20. #include "../test_function/check_equal_fn.hpp"
  21. namespace boost
  22. {
  23. namespace
  24. {
  25. template< class Range >
  26. unsigned int udistance(Range& rng)
  27. {
  28. return static_cast<unsigned int>(boost::distance(rng));
  29. }
  30. template< class SinglePassRange >
  31. void test_for_each_impl( SinglePassRange rng )
  32. {
  33. using namespace boost::range_test_function;
  34. typedef check_equal_fn< SinglePassRange > fn_t;
  35. // Test the mutable version
  36. fn_t result_fn = boost::for_each(rng, fn_t(rng));
  37. BOOST_CHECK_EQUAL( boost::udistance(rng), result_fn.invocation_count() );
  38. fn_t result_fn2 = boost::for_each(boost::make_iterator_range(rng), fn_t(rng));
  39. BOOST_CHECK_EQUAL( boost::udistance(rng), result_fn2.invocation_count() );
  40. // Test the constant version
  41. const SinglePassRange& cref_rng = rng;
  42. result_fn = boost::for_each(cref_rng, fn_t(cref_rng));
  43. BOOST_CHECK_EQUAL( boost::udistance(cref_rng), result_fn.invocation_count() );
  44. }
  45. template< class Container >
  46. void test_for_each_t()
  47. {
  48. using namespace boost::assign;
  49. // Test empty
  50. Container cont;
  51. test_for_each_impl(cont);
  52. // Test one element
  53. cont += 0;
  54. test_for_each_impl(cont);
  55. // Test many elements
  56. cont += 1,2,3,4,5,6,7,8,9;
  57. test_for_each_impl(cont);
  58. }
  59. void test_for_each()
  60. {
  61. boost::array<int, 10> a = {{ 0,1,2,3,4,5,6,7,8,9 }};
  62. test_for_each_impl(a);
  63. test_for_each_t< std::vector<int> >();
  64. test_for_each_t< std::list<int> >();
  65. test_for_each_t< std::set<int> >();
  66. test_for_each_t< std::multiset<int> >();
  67. }
  68. }
  69. }
  70. boost::unit_test::test_suite*
  71. init_unit_test_suite(int argc, char* argv[])
  72. {
  73. boost::unit_test::test_suite* test
  74. = BOOST_TEST_SUITE( "RangeTestSuite.algorithm.for_each" );
  75. test->add( BOOST_TEST_CASE( &boost::test_for_each ) );
  76. return test;
  77. }