简体   繁体   中英

C++ loop through objects and obtain their addresses

I have the following code snippet:

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

triangle is a class derived from shape class, and triangles is an std::vector of triangles:

std::vector<triangle> triangles;

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

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);
} 

you make a copy in each iteration, change your loop to:

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

您将获取本地临时变量的地址,将x的类型更改为auto&然后您将获得对vector元素的引用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM