Sign in to follow this  

Pointers to Vector Elements

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

This topic is 3597 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this