Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting pointers to vector elements [duplicate]

I run into an issue which I don't quite understand:

I am creating an object Edge with

edge_vec1.push_back(Edge(src,dest));

Then I want to keep a pointer to this Edge in a separate vector:

edge_vec2.push_back(&edge_vec1.back());

However, once I add the second Edge object, the pointer to the first Edge in edge_vec2 is invalidated(gets some random data). Is it because the pointer in edge_vec2 actually points to some place in edge_vec1, and not the underlying element? I can avoid this by creating my Edge objects on the heap, but I'd like to understand what's going on.

Thank you.

like image 716
LazyCat Avatar asked Mar 09 '23 00:03

LazyCat


2 Answers

When a new element is added to a vector then the vector can be reallocated. So the previous values of pointers to the elements of the vector can be invalid.

You should at first reserve enough memory for the vector preventing the reallocation.

edge_vec2.reserve( SomeMaxValue );
like image 142
Vlad from Moscow Avatar answered Apr 08 '23 06:04

Vlad from Moscow


From http://en.cppreference.com/w/cpp/container/vector/push_back:

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.

It's a bad idea to depend on pointers/references to objects in a vector when you are adding items to it. It is better to store the value of the index and then use the index to fetch the item from the vector.

edge_vec2.push_back(edge_vec1.size()-1);

Later, you can use:

edge_vec1[edge_vec2[i]]

for some valid value of i.

like image 35
R Sahu Avatar answered Apr 08 '23 07:04

R Sahu