Home > C++, VC++ > How to convert iterator to corresponding data pointer?

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.

typedef std::vector<int> 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();&#91;/sourcecode&#93;

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...

&#91;sourcecode language="cpp"&#93;// 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;

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 😦

Categories: C++, VC++ Tags: , , ,
  1. hribek
    January 21, 2009 at 7:00 am

    C++ stdlib distance(iterator, iterator) is way to go ;).

    • January 21, 2009 at 7:01 am

      Thanks Hribek. I’ll have a look at it.

  2. September 9, 2008 at 4:23 am

    >> 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!

  3. TRi
    September 5, 2008 at 10:06 pm

    hello, I wonder there is a way to convert from data pointer back to iterator ? Thanks

  4. shi
    August 8, 2008 at 7:55 pm

    Is this safe ? (I have no idea, just being curious)

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: