Click to See Complete Forum and Search --> : vector headache - please help


bubble_butt
November 18th, 2001, 02:58 PM
I have a List Control in my program. Each List Control item corresponds to a vector element. When I push_back() an element on the vector and insert an item for it into the List Control, I take the following pointer to the element,(myVectorElement*) &myVector.back(), and set the list control item data (SetItemData()) so I have a pointer to it. For some reason, when I call GetItemData() to re-retrieve the pointer - it is invalid. Can I rely on the pointer I am getting back from (myVectorElement*) &myVector.back() to always reference the element I originally pushed onto the vector?

Thanks

Igor Soukhov
November 18th, 2001, 06:07 PM
As long as you're not doing some "weird" operation which can cause reallocations of elements in a vector e.g. insert, clear, erase or not apply modifying algoritms (like sort, remove, etc) - you can rely on the pointer you've got.

NB: push_back you're using internally implemented using insert member function, BUT as long as you're inserting elements into the BACK of container no reallocations occurs...

And in you're case - may be something wrong with a code that sets a data in List control?

Please - rate answer if it helped you
It gives me inspiration when I see myself in the top list =)

Best regards,

-----------
Igor Soukhov (Brainbench/Tekmetrics ID:50759)
igor@soukhov.com | ICQ:57404554 | http://soukhov.com

Russian Software Developer Network http://rsdn.ru

James Curran
November 18th, 2001, 09:07 PM
In reply to:

(myVectorElement*) &myVector.back()



If I followed your message right, what you want is:*(myVector.back())

And you should not need the cast.

Truth,
James
http://www.NJTheater.com
http://www.NovelTheory.com
I don't do it for the points (OK, maybe I do), but rating a post is a good way for me to know if I helped.

Graham
November 19th, 2001, 03:23 AM
If you want a pointer to an element in a vector, why not use an iterator?

vector<MyClass>::iterator = myvec.end() - 1;



This should point to the back element. Beware of operations that invalidate iterators, though.

He who breaks a thing to find out what it is, has left the path of wisdom - Gandalf