2011-03-23 112 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; 
    } 
}