Get a pointer to STL container an iterator is referencing?

后端 未结 3 786
感动是毒
感动是毒 2020-12-11 01:06

For example, the following is possible:

std::set s;  
std::set::iterator it = s.begin();

I wonder if the opposite is

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 01:36

    It is possible with at least one of the std iterators and some trickery. The std::back_insert_iterator needs a pointer to the container to call its push_back method. Moreover this pointer is protected only.

    #include 
    
    template 
    struct get_a_pointer_iterator : std::back_insert_iterator {
        typedef std::back_insert_iterator base;
        get_a_pointer_iterator(Container& c) : base(c) {}
        Container* getPointer(){ return base::container;}
    };
    
    #include 
    int main() {
        std::vector x{1};
        auto p = get_a_pointer_iterator>(x);
        std::cout << (*p.getPointer()).at(0);
    }
    

    This is of course of no pratical use, but merely an example of an std iterator that indeed carries a pointer to its container, though a quite special one (eg. incrementing a std::back_insert_iterator is a noop). The whole point of using iterators is not to know where the elements are coming from. On the other hand, if you ever wanted an iterator that lets you get a pointer to the container, you could write one.

提交回复
热议问题