Jump to content
  • Advertisement
Sign in to follow this  
v0dKA

Question about std::vector

This topic is 4588 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Given a pointer to an element of a vector, is it possible to figure out the offset of that element in the original vector?

Share this post


Link to post
Share on other sites
Advertisement
offset = iter-myVector.begin();

(Although one of the resident c++ gurus may pop in and explain that the above is a bad idea for one reason or another...)

[Edit: If it's a pointer that you have rather than an iterator, perhaps 'offset = ptr-&myVector[0]'. But depending on what you're trying to do, there's probably a way to do it while still using stl functionality and syntax. Perhaps you could describe the context.]

Share this post


Link to post
Share on other sites
With iterators I think the C++ way is with the distance function. Since it works with non-random iterators.


vector<int> myVector(10);
int *pointer=&myVector[9];
cout << pointer-&myVector[0]; //prints 9,

Of the STD countains this only works with vectors.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!