getting pointers to vector elements

Viewed 3070

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.

3 Answers
Related