How to convert iterator to corresponding data pointer?

Well it was quite easy in VC6 to work with iterators since iterators were actual pointers to internal data, so they could be used interchangeably.

For e.g.

[sourcecode language=”cpp”]typedef std::vector IntVector;
IntVector IntVecObj;

// Push in a thousand ints
for( int Index = 0; Index < 1000; ++Index ) {    IntVecObj.push_back( Index + 1 ); } // Access internal pointer int *p = IntVecObj.begin();[/sourcecode] But above code gives error if compiled in VC8! Says cannot convert from vector::iterator type to int*. Mmm, so how can we get the internal pointer? This is what I've done... [sourcecode language="cpp"]// Following code snippet won't compile in VC6 hence the compilation guard #if _MSC_VER >= 1400 // VC8 onwards
int* p = &(*IntVecObj.begin());
// Or // int* p = IntVecObj.begin()._Myptr;
++*p;
#endif[/sourcecode]

You may ask why I had to take this approach? I am currently migrating a project from VC6 to VC8 hence plenty of code which directly uses pointers as iterators and iterators as pointers, so this helps. 🙂

I’ve got to say it’s a pain to work with new version of these stl classes, of course it could all turn out for good, sigh! anyway 🙁

5 thoughts on “How to convert iterator to corresponding data pointer?

  1. >> TRi,

    It’s bad to convert pointer to iterator. Since iterators will be having additional information which you can miss out. So it’s best to use iterator as they are meant to be. It’s just not safe!

Appreciate your comments...