indexed_example.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. //[indexed_example
  12. //<-
  13. #include <boost/config.hpp>
  14. //->
  15. #include <boost/range/adaptor/indexed.hpp>
  16. #include <boost/assign.hpp>
  17. #include <iterator>
  18. #include <iostream>
  19. #include <vector>
  20. //<-
  21. #include <boost/test/test_tools.hpp>
  22. #include <boost/test/unit_test.hpp>
  23. namespace
  24. {
  25. template<class Iterator1, class Iterator2>
  26. void check_element_and_index(
  27. Iterator1 test_first,
  28. Iterator1 test_last,
  29. Iterator2 reference_first,
  30. Iterator2 reference_last)
  31. {
  32. BOOST_CHECK_EQUAL( std::distance(test_first, test_last),
  33. std::distance(reference_first, reference_last) );
  34. std::ptrdiff_t reference_index = 0;
  35. Iterator1 test_it = test_first;
  36. Iterator2 reference_it = reference_first;
  37. for (; test_it != test_last; ++test_it, ++reference_it, ++reference_index)
  38. {
  39. BOOST_CHECK_EQUAL(test_it->value(), *reference_it);
  40. BOOST_CHECK_EQUAL(test_it->index(), reference_index);
  41. }
  42. }
  43. template<class SinglePassRange1, class SinglePassRange2>
  44. void check_element_and_index(
  45. const SinglePassRange1& test_rng,
  46. const SinglePassRange2& reference_rng)
  47. {
  48. check_element_and_index(
  49. boost::begin(test_rng), boost::end(test_rng),
  50. boost::begin(reference_rng), boost::end(reference_rng));
  51. }
  52. //->
  53. //<-
  54. void indexed_example_test()
  55. //->
  56. //=int main(int argc, const char* argv[])
  57. {
  58. using namespace boost::assign;
  59. using namespace boost::adaptors;
  60. std::vector<int> input;
  61. input += 10,20,30,40,50,60,70,80,90;
  62. //<-
  63. #ifndef BOOST_NO_CXX11_RANGE_BASED_FOR
  64. //->
  65. for (const auto& element : input | indexed(0))
  66. {
  67. std::cout << "Element = " << element.value()
  68. << " Index = " << element.index()
  69. << std::endl;
  70. }
  71. //<-
  72. #endif // C++11 has range for loop
  73. //->
  74. //= return 0;
  75. //=}
  76. //]
  77. check_element_and_index(
  78. input | indexed(0),
  79. input);
  80. }
  81. }
  82. boost::unit_test::test_suite*
  83. init_unit_test_suite(int argc, char* argv[])
  84. {
  85. boost::unit_test::test_suite* test
  86. = BOOST_TEST_SUITE( "RangeTestSuite.adaptor.indexed_example" );
  87. test->add( BOOST_TEST_CASE( &indexed_example_test ) );
  88. return test;
  89. }