C ++ traverse objects and get their addresses

I have the following piece of code:

vector<shape*> triangle_ptrs;
for (auto x : triangles)
    triangle_ptrs.push_back(&x);

      

triangle

is the class derived from the class shape

, and triangles

is the triangle std::vector

:

std::vector<triangle> triangles;

      

I need to store the addresses of the triangles, but as I go through the collection, their addresses seem to be the same. How do I get around this?

+3


source to share


2 answers


In this loop:

for (auto x : triangles)
    triangle_ptrs.push_back(&x);

      

which is logically equal to:



for ( auto it = triangles.begin(), it != triangles.end(); ++it) { 
    auto x  = *it; 
    triangle_ptrs.push_back(&x);
} 

      

make a copy on each iteration, change your loop to:

for (auto &x : triangles)
    triangle_ptrs.push_back(&x);

      

+6


source


You get the address of a local temporary variable, change the type x

to auto&

, after which you get a link to vector elements.



+1


source







All Articles