2017-04-12 74 views
3

我有下面的代碼片斷:C++遍歷目標並獲得它們的地址

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

triangle是從shape類派生的類,和triangles是三角形的std::vector

std::vector<triangle> triangles; 

我需要保存三角形的地址,但是當我循環訪問集合時,它們的地址似乎是相同的。我該如何解決這個問題?

+3

'x'是你正在循環的三角形的副本。使用'auto&x'獲得對原始三角形的引用並獲取所需的指針。 – nwp

+0

請用[最小,可驗證和完整的示例](https://stackoverflow.com/help/mcve)擴展您的帖子。 –

+0

'auto&x'而不是'auto x'中的範圍for循環 – Raxvan

回答

6

在這個循環中:

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

你是獲取本地臨時變量的地址,將x的類型更改爲auto&然後你得到一個向量元素的引用。