| 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 | #if !BOOST_STL_INTERFACES_USE_DEDUCED_THIS |
| 16 | repeated_chars_iterator, |
| 17 | #endif |
| 18 | std::random_access_iterator_tag, |
| 19 | char, |
| 20 | char> |
| 21 | { |
| 22 | constexpr repeated_chars_iterator() noexcept : |
| 23 | first_(nullptr), |
| 24 | size_(0), |
| 25 | n_(0) |
| 26 | {} |
| 27 | constexpr repeated_chars_iterator( |
| 28 | char const * first, difference_type size, difference_type n) noexcept : |
| 29 | first_(first), |
| 30 | size_(size), |
| 31 | n_(n) |
| 32 | {} |
| 33 | |
| 34 | constexpr char operator*() const noexcept { return first_[n_ % size_]; } |
| 35 | constexpr repeated_chars_iterator & operator+=(std::ptrdiff_t i) noexcept |
| 36 | { |
| 37 | n_ += i; |
| 38 | return *this; |
| 39 | } |
| 40 | constexpr auto operator-(repeated_chars_iterator other) const noexcept |
| 41 | { |
| 42 | return n_ - other.n_; |
| 43 | } |
| 44 | |
| 45 | private: |
| 46 | char const * first_; |
| 47 | difference_type size_; |
| 48 | difference_type n_; |
| 49 | }; |
| 50 | //] |
| 51 | |
| 52 | |
| 53 | int main() |
| 54 | { |
| 55 | //[ repeated_chars_iterator_usage |
| 56 | repeated_chars_iterator first("foo" , 3, 0); // 3 is the length of "foo", 0 is this iterator's position. |
| 57 | repeated_chars_iterator last("foo" , 3, 7); // Same as above, but now the iterator's position is 7. |
| 58 | std::string result; |
| 59 | std::copy(first: first, last: last, result: std::back_inserter(x&: result)); |
| 60 | assert(result == "foofoof" ); |
| 61 | //] |
| 62 | } |
| 63 | |