distance_test.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright (C) 2017 Michel Morin.
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. #include <vector>
  7. #include <list>
  8. #include <boost/container/slist.hpp>
  9. #include <boost/core/lightweight_test.hpp>
  10. #include <boost/iterator/distance.hpp>
  11. #include <boost/iterator/transform_iterator.hpp>
  12. int twice(int x) { return x + x; }
  13. template <typename Iterator>
  14. void test_distance(Iterator it_from, Iterator it_to, int n)
  15. {
  16. BOOST_TEST(boost::distance(it_from, it_to) == n);
  17. }
  18. int main()
  19. {
  20. int array[3] = {1, 2, 3};
  21. int* ptr1 = array;
  22. int* ptr2 = array + 3;
  23. {
  24. test_distance(ptr1, ptr2, 3);
  25. test_distance(ptr2, ptr1, -3);
  26. test_distance(
  27. boost::make_transform_iterator(ptr1, twice)
  28. , boost::make_transform_iterator(ptr2, twice)
  29. , 3
  30. );
  31. test_distance(
  32. boost::make_transform_iterator(ptr2, twice)
  33. , boost::make_transform_iterator(ptr1, twice)
  34. , -3
  35. );
  36. }
  37. {
  38. std::vector<int> ints(ptr1, ptr2);
  39. test_distance(ints.begin(), ints.end(), 3);
  40. test_distance(ints.end(), ints.begin(), -3);
  41. test_distance(
  42. boost::make_transform_iterator(ints.begin(), twice)
  43. , boost::make_transform_iterator(ints.end(), twice)
  44. , 3
  45. );
  46. test_distance(
  47. boost::make_transform_iterator(ints.end(), twice)
  48. , boost::make_transform_iterator(ints.begin(), twice)
  49. , -3
  50. );
  51. }
  52. {
  53. std::list<int> ints(ptr1, ptr2);
  54. test_distance(ints.begin(), ints.end(), 3);
  55. test_distance(
  56. boost::make_transform_iterator(ints.begin(), twice)
  57. , boost::make_transform_iterator(ints.end(), twice)
  58. , 3
  59. );
  60. }
  61. {
  62. boost::container::slist<int> ints(ptr1, ptr2);
  63. test_distance(ints.begin(), ints.end(), 3);
  64. test_distance(
  65. boost::make_transform_iterator(ints.begin(), twice)
  66. , boost::make_transform_iterator(ints.end(), twice)
  67. , 3
  68. );
  69. }
  70. return boost::report_errors();
  71. }