Sign in to follow this  

Pointer to an item in an std::vector

This topic is 3553 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 use C++. Let's say I have a vector of ints.
vector <int> int_vector;
int_vector.push_back(3);
int_vector.push_back(4);
int_vector.push_back(5);

Now I make a pointer to...the second int.
int* ptr = &int_vector[1];

If add another int to the vector after that, like "int_vector.push_back(6);", does that invalidate my pointer? Should I not be making pointers to items in a vector anyway? I believe this is causing some weird behavior I'm experiencing right now. Also, what then is the best way to refer to items in a vector? I would just use an index (like make an int that counts from the beginning of the vector (0) to the item I want), but that index is invalidated any time I delete an item before it. Edit: I think iterators might be the answer?

Share this post


Link to post
Share on other sites
iterator/pointers into a vector are invalidated whenever it is resized. Therefore any operation which might potentially cause a vector to resize itself should be assumed to invalidate all iterators (or pointers) to the contents of the vector.

If you don't want this behavior you'll need to use another container like a std::list. List never invalidates iterators to any of it's elements (except obviously iterators to deleted elements are invalid).

Alternatively you could maintain a vector of pointers (or better yet smart pointers, or even better boost::ptr_vector)

Share this post


Link to post
Share on other sites
If you feel you have a need to hang on to a pointer, iterator, or reference to a particular item in a vector whilst the contents of that vector changes, then you probably need to re-examine what you are doing. If you simply want to be able to look that item up again quickly then you may just need to change the container type to say a set or a map. We'd need to see more code to get an idea of what would be best in this case.

Share this post


Link to post
Share on other sites

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