Skip to main content
GameDev.net gamedev.net
🔒 Locked

Pointer to an item in an std::vector

Started by ouraqt Mar 24, 2008 at 11:02 PM 1 replies 15.1k views
Original Post
ouraqt
ouraqt
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 = ∫_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?
cshowe
cshowe
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)
iMalc
iMalc
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.