2015-11-18 105 views
0

什麼是c++11範圍內環路也導致此:關於C++ 11範圍內循環和迭代

std::list<Point> item; 
.... 
//fill the list somewhere else 
.... 
for(Point p : item) { 
    p.lowerY(); 
} 

若要僅一次(即lowerY()做什麼它應該只有一次這樣做,但下一次達到這個循環時,它什麼都不做),但是這個:

list<Point>::iterator it; 
for (it = item.begin();it != item.end();++it) { 
    it->lowerY(); 
} 

每次都很完美。有什麼不同?

+2

我想..這是因爲你得到'按值p'(所以..如果'lowerY'應該改變原始點上的東西..它不會影響原來的)。嘗試使用'Point&p'。 – wendelbsilva

+0

是的,修復它,我看到了,所以它製作了原件的副本並改變了它。 @wendelbsilva – shinzou

回答

1

在你以前的代碼中,行

for(Point p : item) { 

創建點的副本,每一次進入下一個項目的時間。爲了確保你的方法LOWERY的調用()的作品,你需要重新定義它作爲

for(Point & p : item) { 
+1

作爲進一步的說明,你可能會遇到與for(auto p:item){...}相同的問題,因爲這可以用作for(Point p:item){}',所以你會想用'for(auto&p:item){...}'代替。 –