2011-11-07 52 views
2

我可以使用c的參考變量(例如,Customer &c)嗎?如果是這樣如何?這是更喜歡使用指針變量?C++參考vs指針for循環內變量?

for(std::vector<Customer*>::const_iterator it = customers_.begin(); 
     it != customers_.end() ; it ++) 
    { 
     Customer *c = (*it); 
     c->PrintName(); 
     ... 
    } 
+0

爲什麼不直接使用迭代器? IT-> PrintName(); – Ferruccio

+0

@Ferruccio:因爲迭代器引用了一個指針,而不是一個對象。你必須做'(* it) - >' –

+0

我明白了。我錯過了。 – Ferruccio

回答

6

是:

for(std::vector<Customer*>::const_iterator it = customers_.begin(); 
    it != customers_.end() ; it ++) 
{ 
    Customer &c = *(*it); 
    c.PrintName(); 
    ... 
} 

(括號是沒有必要的,但可能會更清楚。)

+1

沒有必要的parens。 :) – Xeo

+0

它應該是'const Customer&c',我認爲'it'是'const_iterator'。 – Nawaz

+0

@Xeo:Jinx!.... –

3

您可以:

for(std::vector<Customer*>::const_iterator it = customers_.begin(); 
    it != customers_.end() ; it ++) 
{ 
    Customer const &c = **it; 
    c.PrintName(); 
    ... 
} 

你可能不想要這樣做。 customers_應該是vector<Customer>而不是vector<Customer *>,而不是呼叫其PrintName成員,您應該將operator<<重載爲Customer。完成之後,您將可以使用類似於:

std::copy(customers_.begin(), customers.end(), 
      std::ostream_iterator<Customer>(std::cout, "\n")); 
+0

+1好點。我已經經歷了很多我的代碼,並從引用語義轉換爲值語義。我正在看的特定代碼我不確定這是否可能,但我會牢記它。也開始學習算法的使用,儘管它們並不總是立即顯而易見,不管它們是幫助還是傷害可讀性。 – User

+0

@User:在C++ 03中,這通常是可辯論的(尤其是從'for_each'調用成員函數與使用顯式循環相比)。在C++ 11中,我很少看到一種算法效果不好的情況(我懷疑有一次我知道lambda表達式更好,儘管很少有持久性可能會消失)。 –

+0

您添加到引用變量的'const'是否無法調用Customer的非const方法?如果是這樣,這是不同於我原來的代碼的行爲,雖然我可能能夠在其他循環中使用這個事實。 – User