vector<int> vi;
typedef vector<int>::iterator Iter;
typedef vector<int>::const_iterator ConstIter;
Iter i;
ConstIter ci;
Copy the code

Casting I = (const_cast<Iter>(ci)) causes a compilation error. A const_iterator cannot be cast to iterator.

In STL, the correct conversion method is:

i = vi.begin();
advance(i, distance<ConstIter>(i,ci) );
Copy the code

This method is very simple and straightforward. To get an iterator that points to the same position as a const_iterator, first create a new iterator that points to the original position of the container, then take the offset from the original position of the container and move the iterator forward by the same offset as a const_iterator.

Where advance and distance are in the <iterator> header. Distance is used to calculate the distance between two iterators, and advance is used to move an iterator by a specified distance.

For randomly accessed iterators (vector, string, deque), the time of this method is constant time. For a bidirectional iterator (unordered_map), time is linear.