• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2019 T. Zachary Laine
2 //
3 // Distributed under the Boost Software License, Version 1.0. (See
4 // accompanying file LICENSE_1_0.txt or copy at
5 // http://www.boost.org/LICENSE_1_0.txt)
6 //[ random_access_iterator
7 #include <boost/stl_interfaces/iterator_interface.hpp>
8 
9 #include <algorithm>
10 #include <array>
11 
12 #include <cassert>
13 
14 
15 // This is a minimal random access iterator.  It uses default template
16 // parameters for most stl_interfaces template parameters.
17 struct simple_random_access_iterator
18     : boost::stl_interfaces::iterator_interface<
19           simple_random_access_iterator,
20           std::random_access_iterator_tag,
21           int>
22 {
23     // This default constructor does not initialize it_, since that's how int *
24     // works as well.  This allows optimum performance in code paths where
25     // initializing a single pointer may be measurable.  It is also a
26     // reasonable choice to initialize with nullptr.
simple_random_access_iteratorsimple_random_access_iterator27     simple_random_access_iterator() noexcept {}
simple_random_access_iteratorsimple_random_access_iterator28     simple_random_access_iterator(int * it) noexcept : it_(it) {}
29 
operator *simple_random_access_iterator30     int & operator*() const noexcept { return *it_; }
operator +=simple_random_access_iterator31     simple_random_access_iterator & operator+=(std::ptrdiff_t i) noexcept
32     {
33         it_ += i;
34         return *this;
35     }
operator -simple_random_access_iterator36     auto operator-(simple_random_access_iterator other) const noexcept
37     {
38         return it_ - other.it_;
39     }
40 
41 private:
42     int * it_;
43 };
44 
45 
main()46 int main()
47 {
48     std::array<int, 10> ints = {{0, 2, 1, 3, 4, 5, 7, 6, 8, 9}};
49 
50     simple_random_access_iterator first(ints.data());
51     simple_random_access_iterator last(ints.data() + ints.size());
52     std::sort(first, last);
53     assert(ints == (std::array<int, 10>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}));
54 }
55 //]
56