# Pointer to an item in an std::vector

## Recommended Posts

ouraqt    236
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
cshowe    360
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 on other sites
iMalc    2466
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.