2012-02-12 121 views
0

我有下面的代碼在我的項目:迭代與非迭代循環,不同的輸出,C++

std::cout << "Without iterator:\n"; 

std::vector<RectangleCluster*> rc = p->getInnerRegionPolygons().at(0)->getClusters(); 

for (int i = 0; i < rc.size(); i++) 
    std::cout << "Cluster " << rc.at(i)->getId() << ": start = " << rc.at(i)->getOverlapAtStart() << ", end = " << rc.at(i)->getOverlapAtEnd() << std::endl; 

std::cout << "\n\nWith iterator:\n"; 

for (std::vector<RectangleCluster*>::iterator ci = p->getInnerRegionPolygons().at(0)->getClusters().begin(); ci != p->getInnerRegionPolygons().at(0)->getClusters().end(); ++ci) 
    std::cout << "Cluster " << (*ci)->getId() << ": start = " << (*ci)->getOverlapAtStart() << ", end = " << (*ci)->getOverlapAtEnd() << std::endl; 

控制檯輸出看起來是這樣的:

沒有迭代器:
集羣0:開始= 65.4238,端= 64.9811
羣集1:開始= 64.9811,端= 17.9983
羣集2:開始= 17.9983,端= 17.9983 ...

隨着迭代:
羣集34026352:開始= 1.68113e-316,末端= 1.68113e-316
羣集1:開始= 64.9811,端= 17.9983
羣集2:開始= 17.9983,端= 17.9983 ...

「...」之後的輸出也相同。爲什麼沒有迭代器的代碼給我「集羣0:開始= 65.4238,結束= 64.9811」和迭代器「集羣34026352:開始= 1.68113e-316,結束= 1.68113e-316」的代碼?

for (std::vector<RectangleCluster*>::iterator ci = rc.begin(); ci != rc.end(); ++ci) 
    std::cout << "Cluster " << (*ci)->getId() << ": start = " << (*ci)->getOverlapAtStart() << ", end = " << (*ci)->getOverlapAtEnd() << std::endl; 

我同意awoodland的評論:

問候 的Gernot

+2

這裏沒有足夠的信息來說明任何確定性。 (通常一個*最小的*完整的例子使問題更容易回答)。在(0) - > getClusters()是否通過值或引用返回'p-> getInnerRegionPolygons()。我打賭前者 – Flexo 2012-02-12 10:04:28

+0

如果這是有價值的,你的迭代器初始化爲一個向量副本,檢查是針對另一個副本的另一個迭代器結束!不知道在這種情況下有什麼效果。你可以嘗試通過初始化數組到單個變量並使用迭代器或暴露p-> getInnerRegionPolygons()。at(0)的接口來提供迭代器? – PermanentGuest 2012-02-12 10:32:33

回答

3

請像迭代器重寫代碼。在(0) - > getClusters()中,最有可能的是p-> getInnerRegionPolygons()。每次調用都會返回新的向量。從(...)運算符的不同容器內部比較迭代器是不正確的。