C++ iterator to const_iterator

后端 未结 2 1218
别那么骄傲
别那么骄傲 2020-12-18 18:55

How do I acquire a const_iterator (of some container class) from an iterator (of that container class) in C++? What about a const_iterator

2条回答
  •  醉梦人生
    2020-12-18 19:18

    Containers are required to provide iterator as a type convertible to const_iterator, so you can convert implicitly:

    Container::iterator it = /* blah */;
    Container::const_iterator cit = it;
    

    std::insert_iterators are output iterators. This gives no way to convert them to a regular Container::iterator which must be a forward iterator.

    Another kind of insert iterator may allow such a thing, but those obtained from the standard functions don't.

    I guess you can write your own wrapper around std::insert_iterator that exposes the protected member iter, though:

    template 
    class exposing_insert_iterator : public std::insert_iterator {
    public:
        exposing_insert_iterator(std::insert_iterator it)
        : std::insert_iterator(it) {}
        typename Container::iterator get_iterator() const {
            return std::insert_iterator::iter;
        }
    };
    
    // ...
    std::insert_iterator ins_it;
    exposing_insert_iterator exp_it = ins_it;
    Container::iterator it = exp_it.get_iterator();
    

提交回复
热议问题