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