• 12
• 12
• 9
• 10
• 13

# Pointer to an item in an std::vector

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

## 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 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)