Constant iterators can't be converted directly to an non-constant iterator, but there is a round-about conversion technique available.
The std::advance(i, n)
function advances the iterator i
by n
;
std::advance()
works for any iterator category. The std::distance(i,
j)
function returns the distance between the iterators i
and j
; as
with std::advance()
, std::distance()
works for any iterator category (as
long as both iterators refer to the same container).
I think you can see where this is heading. If you have a constant iterator
ci
, you can find the equivalent non-constant iterator by doing
C::iterator i = c.begin(); std::advance(i, std::distance(i, ci));
This technique requires that you know both the container from which the constant iterator came, and the container's type (and that the container itself be non-constant). This isn't that big a deal if you're dealing with templates, but it can get clumsy if you're not.
Unfortunately, the technique as described here is a bit too simple to work; it
requires some fancy dancing to get around a template-matching problem in
std::distance()
. However, rather than describe the fix here, I'll just
point you to Item 27 in Scott Meyer's Effective STL, which describes the
technique in all its glory.
This page last modified on 25 February 2004.