C++ 遍历对象并获取它们的地址
C++ loop through objects and obtain their addresses
我有以下代码片段:
vector<shape*> triangle_ptrs;
for (auto x : triangles)
triangle_ptrs.push_back(&x);
triangle
是从 shape
class 导出的 class,triangles
是三角形的 std::vector
:
std::vector<triangle> triangles;
我需要保存三角形的地址,但当我遍历集合时,它们的地址似乎是相同的。我该如何解决这个问题?
在此循环中:
for (auto x : triangles)
triangle_ptrs.push_back(&x);
逻辑上等于:
for ( auto it = triangles.begin(), it != triangles.end(); ++it) {
auto x = *it;
triangle_ptrs.push_back(&x);
}
你在每次迭代中制作一个副本,将你的循环更改为:
for (auto &x : triangles)
triangle_ptrs.push_back(&x);
您正在获取局部临时变量的地址,将 x
的类型更改为 auto&
然后您将获得对向量元素的引用。
我有以下代码片段:
vector<shape*> triangle_ptrs;
for (auto x : triangles)
triangle_ptrs.push_back(&x);
triangle
是从 shape
class 导出的 class,triangles
是三角形的 std::vector
:
std::vector<triangle> triangles;
我需要保存三角形的地址,但当我遍历集合时,它们的地址似乎是相同的。我该如何解决这个问题?
在此循环中:
for (auto x : triangles)
triangle_ptrs.push_back(&x);
逻辑上等于:
for ( auto it = triangles.begin(), it != triangles.end(); ++it) {
auto x = *it;
triangle_ptrs.push_back(&x);
}
你在每次迭代中制作一个副本,将你的循环更改为:
for (auto &x : triangles)
triangle_ptrs.push_back(&x);
您正在获取局部临时变量的地址,将 x
的类型更改为 auto&
然后您将获得对向量元素的引用。