Use reverse_iterator with erase type

I have a class that contains and controls a series of objects. To avoid data leakage of these objects, allowing them to pass through them, I decided to use type erasure with boost::any_iterator.

 using my_erased_type_iterator = boost::range_detail::any_iterator<
    MyClass,
    boost::bidirectional_traversal_tag,
    MyClass&, 
    std::ptrdiff_t>;

I defined a function Begin()and End()in MyClassthat just returns the container Begin()and End()as a function my_erased_type_iterator. It works exactly the way I want, and no one MyClassknows that I use a vector to store objects, and they do not have access to the container, except for the functions that I open in the interface MyClass.

Now, for a number of reasons, I need to do the reverse repetition of objects. I also need to know the next element after the inverse iterator (akin to calling std::next()on a normal iterator, which is no longer so trivial for inverse iterators), and I may also need to call functions such as erase()on this inverse iterator.

So for my question: is there an elegant way to use style-erasing along with reverse iterators (and the const version of both forward and backward)? Should I use direct erase iterators and loop back instead? It occurred to me that I could solve this problem incorrectly, so I am open to any suggestions or to clarify my questions, if necessary.

+4
2

, any_iterator - .

, any_range<>, API .

1. make_reverse_iterator

make_reverse_iterator

Live On Coliru

#include <boost/range.hpp>
#include <boost/range/any_range.hpp>

struct MyClass {
    int i;
};

using my_erased_type_iterator = boost::range_detail::any_iterator<
    MyClass,
    boost::bidirectional_traversal_tag,
    MyClass&, 
    std::ptrdiff_t>;

#include <iostream>
#include <vector>

int main() {
    using namespace boost;
    std::vector<MyClass> const v { {1}, {2}, {3}, {4} };

    for (auto& mc : make_iterator_range(
                make_reverse_iterator(v.end()),
                make_reverse_iterator(v.begin())))
    {
        std::cout << mc.i << " ";
    }
}

4 3 2 1 

2. reversed:

any_range<>:

Live On Coliru

int main() {
    std::vector<MyClass> const v { {1}, {2}, {3}, {4} };

    boost::any_range_type_generator<decltype(v)>::type x = reverse(v);

    for (my_erased_type_const_iterator f = boost::begin(x), l = boost::end(x); f!=l; ++f) {
        std::cout << f->i << " ";
    }

}
+1

.

.base(), , , .

, ( ) . italafor invalidadion - , , ! (, , ). Swappimng , , .

+1

Source: https://habr.com/ru/post/1626079/


All Articles