Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ iterator to const_iterator

Tags:

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 from an insert_iterator? The resulting iterator should point at the same spot as the original does.

like image 287
Thomas Eding Avatar asked Oct 13 '11 19:10

Thomas Eding


2 Answers

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 <typename Container> class exposing_insert_iterator : public std::insert_iterator<Container> { public:     exposing_insert_iterator(std::insert_iterator<Container> it)     : std::insert_iterator<Container>(it) {}     typename Container::iterator get_iterator() const {         return std::insert_iterator<Container>::iter;     } };  // ... std::insert_iterator<Container> ins_it; exposing_insert_iterator<Container> exp_it = ins_it; Container::iterator it = exp_it.get_iterator(); 
like image 109
R. Martinho Fernandes Avatar answered Oct 04 '22 03:10

R. Martinho Fernandes


You can convert them. Example:

std::vector<int> v; std::vector<int>::iterator it = v.begin(); std::vector<int>::const_iterator cit = it; 

But I guess that is not the answer you are seeking. Show me code. :-)

like image 27
Florian Avatar answered Oct 04 '22 03:10

Florian