• 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 #include <boost/stl_interfaces/iterator_interface.hpp>
7 
8 #include <string>
9 
10 #include <cassert>
11 
12 
13 //[ repeated_chars_iterator
14 struct repeated_chars_iterator : boost::stl_interfaces::iterator_interface<
15                                      repeated_chars_iterator,
16                                      std::random_access_iterator_tag,
17                                      char,
18                                      char>
19 {
repeated_chars_iteratorrepeated_chars_iterator20     constexpr repeated_chars_iterator() noexcept :
21         first_(nullptr),
22         size_(0),
23         n_(0)
24     {}
repeated_chars_iteratorrepeated_chars_iterator25     constexpr repeated_chars_iterator(
26         char const * first, difference_type size, difference_type n) noexcept :
27         first_(first),
28         size_(size),
29         n_(n)
30     {}
31 
operator *repeated_chars_iterator32     constexpr char operator*() const noexcept { return first_[n_ % size_]; }
operator +=repeated_chars_iterator33     constexpr repeated_chars_iterator & operator+=(std::ptrdiff_t i) noexcept
34     {
35         n_ += i;
36         return *this;
37     }
operator -repeated_chars_iterator38     constexpr auto operator-(repeated_chars_iterator other) const noexcept
39     {
40         return n_ - other.n_;
41     }
42 
43 private:
44     char const * first_;
45     difference_type size_;
46     difference_type n_;
47 };
48 //]
49 
50 
main()51 int main()
52 {
53     //[ repeated_chars_iterator_usage
54     repeated_chars_iterator first("foo", 3, 0); // 3 is the length of "foo", 0 is this iterator's position.
55     repeated_chars_iterator last("foo", 3, 7);  // Same as above, but now the iterator's position is 7.
56     std::string result;
57     std::copy(first, last, std::back_inserter(result));
58     assert(result == "foofoof");
59     //]
60 }
61