错误迭代器的声明在for循环中
问题描述:
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:语法错误:标识符‘它’
如何解决这个问题之前缺少“” ?
答
您不能在for
循环的初始语句中声明多个类型的项目,就像不能将int i = 1, vector<string>::iterator it = vecs.begin();
说成独立语句一样。你必须在循环之外声明其中的一个。
既然你从来没有能够在一个声明,声明不同类型的多个变量C语言(尽管指针是一个相当奇怪的例外):
int i, double d; /* Invalid */
int i, j; /* Valid */
此行为是由C++继承,并适用于for
循环中的每条语句以及独立语句。
答
您的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
答
不能在for循环的“初始化”部分申报两种不同类型的变量。将“我”(或“它”)的声明移到循环外部。
答
您可以使用好的技巧不要让你的迭代器超出范围:
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;
}
}
}
而且我要说的是,如果你需要操作两个元素及其索引更简单的使用索引“为”循环,而不是迭代器。
答
你并不需要统计元素而言,你可以计算从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;
}
}
@Downvoter:为什么的答案都-1'd?他们都是正确的。 – GManNickG 2011-03-23 15:37:35
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
possible [我可以在for循环的初始化中声明不同类型的变量吗?](http://stackoverflow.com/questions/8644707/can-i-declare-variables-of-different-types-in-the-初始化一个for循环) – 2012-08-17 05:43:40