Jump to content
  • Advertisement
Sign in to follow this  
Eddy999999

Pointers to Vector Elements

This topic is 3875 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

I want to create a pointer to a single element in a vector. However, when I erase an element in front of the element being pointed to, the pointer then points to the same numbered element, instead of adjusting to point to the same piece of data. How can I deal with this? Thanks in advance for any help.

Share this post


Link to post
Share on other sites
Advertisement
Either use a container like std::list where erasure and insertion don't invalidate pointers or use a vector of (smart) pointers.

Share this post


Link to post
Share on other sites
Quote:
Original post by Eddy999999
I want to create a pointer to a single element in a vector. However, when I erase an element in front of the element being pointed to, the pointer then points to the same numbered element, instead of adjusting to point to the same piece of data. How can I deal with this? Thanks in advance for any help.
The short answer is: don't store pointers to vector elements. In addition to the problem you mention, pointers may become invalid if the vector re-allocates its internal storage.

If you need to reference elements in the container externally, one option would be to store shared pointers in the container and give out weak pointers to clients (you might also give out shared pointers, depending on the circumstances).

What are the objects in the container? Also, who needs to know about them, and why?

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!