2011-03-23 109 views
1
void catchlabel() 
{ 
    if(vecs.empty()) 
     return; 
    else 
    { 
    cout << "The Sizeof the Vector is: " << vecs.size() << endl; 
    cout << "Currently Stored Labels: " << endl; 
    /* Error 1 */ 
for (int i = 1, vector<string>::iterator it = vecs.begin(); it != vecs.end(); ++it , i++) 
      cout << i << ". "<< *it << endl; 
      cout << endl; 
    } 
} 

我收到以下錯誤:錯誤迭代器的聲明在for循環中

1>錯誤C2146:語法錯誤:標識符‘它’

如何解決這個問題之前缺少「」 ?

+2

@Downvoter:爲什麼的答案都-1'd?他們都是正確的。 – GManNickG 2011-03-23 15:37:35

+0

Duplicate-sh:http://stackoverflow.com/questions/3440066/why-is-it-so-hard-to-write-a-for-loop-in-c-with-2-loop-variables – GManNickG 2011-03-23 15:39:34

+0

possible [我可以在for循環的初始化中聲明不同類型的變量嗎?](http://stackoverflow.com/questions/8644707/can-i-declare-variables-of-different-types-in-the-初始化一個for循環) – 2012-08-17 05:43:40

回答

7

您不能在for循環的初始語句中聲明多個類型的項目,就像不能將int i = 1, vector<string>::iterator it = vecs.begin();說成獨立語句一樣。你必須在循環之外聲明其中的一個。

既然你從來沒有能夠在一個聲明,聲明不同類型的多個變量C語言(儘管指針是一個相當奇怪的例外):

int i, double d; /* Invalid */ 

int i, j; /* Valid */ 

此行爲是由C++繼承,並適用於for循環中的每條語句以及獨立語句。

+0

這是爲什麼呢? – orlp 2011-03-23 15:38:46

+0

@night:看到[this](http://stackoverflow.com/questions/3440066/why-is-it-so-hard-to-write-a-for-loop-in-c-with-2-loop - 變量)。 – GManNickG 2011-03-23 15:44:39

+0

@GMan:對不起,那沒用。這只是解釋說這是不可能的,並解釋瞭解決方法。 OP的編輯解釋它。 – orlp 2011-03-23 15:48:09

1

您的for循環錯誤。您不能在for的初始化部分聲明類型的變量!

這樣做:

int i = 1; 
for (vector<string>::iterator it = vecs.begin(); it != vecs.end(); ++it , i++) 
{ 
     cout << i << ". "<< *it << endl; 
} 

或者,也許,你會愛僅此:

for (size_t i = 0 ; i < vecs.size(); ++i) 
{ 
     cout << (i+1) << ". "<< vecs[i] << endl; 
} 
+4

@Downvoter:請說明原因! – Nawaz 2011-03-23 15:37:33

1

不能在for循環的「初始化」部分申報兩種不同類型的變量。將「我」(或「它」)的聲明移到循環外部。

1

您可以使用好的技巧不要讓你的迭代器超出範圍:

void catchlabel() 
{ 
    if(vecs.empty()) 
     return; 
    else 
    { 
    cout << "The Sizeof the Vector is: " << vecs.size() << endl; 
    cout << "Currently Stored Labels: " << endl; 
    /* Error 1 */ 
    { 
    vector<string>::iterator it = vecs.begin() 
    for (int i = 1; it != vecs.end(); ++it , i++) 
      cout << i << ". "<< *it << endl; 
      cout << endl; 
    } 
    } 
} 

而且我要說的是,如果你需要操作兩個元素及其索引更簡單的使用索引「爲」循環,而不是迭代器。

1

你並不需要統計元素而言,你可以計算從vecs.begin()的距離,當您去:

void catchlabel() 
{ 
    if(!vecs.empty()) 
    { 
        cout << "The Sizeof the Vector is: " << vecs.size() << endl; 
        cout << "Currently Stored Labels: " << endl; 
     for (vector<string>::iterator it = vecs.begin(); it != vecs.end(); ++it) 
      cout << (it - vecs.begin() + 1) << ". "<< *it << endl; 
     cout << endl; 
    } 
}