2011-04-18 51 views
6

我剛剛編譯了GCC 4.6.0,我想嘗試新的功能,從基於範圍的for循環開始。
我想改變的第一個循環是迭代指針的std :: vector。我改變了代碼以使用新的語法,但沒有編譯。C++ 11基於範圍的指針向量

我試圖替換另一個循環,這是一個std ::向量的結構,它編譯和運行完美。

這裏是一個簡短的測試代碼向你展示我的問題:

#include <vector> 
#include <iostream> 

int main() 
{ 
    std::vector<int> values; 

    values.push_back(2); 
    values.push_back(5); 
    values.push_back(8); 
    values.push_back(13); 
    values.push_back(17); 

    for (int &n : values) 
    { 
     std::cout << n << "\n"; 
    } 

    std::vector< int* > pointers; 

    pointers.push_back(new int(2)); 
    pointers.push_back(new int(5)); 
    pointers.push_back(new int(8)); 
    pointers.push_back(new int(13)); 
    pointers.push_back(new int(17)); 

    for ((int*) &p : values) 
    { 
     std::cout << (*p) << "\n"; 
    } 

    for(unsigned int i = 0; i < pointers.size(); ++i) 
    { 
     delete pointers[i]; 
    } 

    return 0; 
} 

當我嘗試編譯(是的,我給-std =的C++ 0x作爲參數傳遞給G ++),它死於此錯誤:
main.cpp|27|error: found ‘:’ in nested-name-specifier, expected ‘::’
如果我將27到30行註釋掉,那沒關係。

我在做什麼錯?不是指針引用聲明的語法正確嗎?
或者是否有基於範圍for循環可以使用的包含類型的限制?

感謝您的幫助!

+1

應該普羅巴bly被轉移到SO – 2011-04-18 19:21:24

+2

@Doug:同意......如果問題包括源代碼,而不是有一個小的URL,它也會有所幫助。 – jprete 2011-04-18 19:23:47

回答

13
for ((int*) &p : values) 

這是不對的。 (int*)只是一個表達式,所以您需要做int*&(沒有括號,表示 - 又名「不是類型名稱」),至少要使其正確。我個人更喜歡使用自動或自動&。

你可以這樣做:

for (auto p : values) // here p is a pointer, a copy of each pointer 

for (auto& p : values) // here p is a non-const reference to a pointer 

for (int* p : values) // here p is a copy of each pointer 

或通用代碼:

for (auto&& p: values) // p is either a const reference to what is in values, or a non-const reference, depends on the context 
+2

'for(auto * p:values)'也適用。 – Sjoerd 2014-05-12 18:54:47

0

我覺得你的意思遍歷「指針」,而不是「價值」那裏......

+0

太糟糕了,只能接受一個答案。你也是對的,我很愚蠢地寫價值而不是指針,但是Klaim的評論更加詳細,並且用圓括號顯示了錯誤。無論如何,非常感謝! – torokati44 2011-04-18 19:47:49