vector<int> v;
for(vector<int>::iterator vi = n.begin(), int i = 0;
vi != n.end();
++vi, ++i){}
为什么不允许这样做呢?我想要定义两个新的计数器,一个是“vi”,另一个是索引“i”。
This is the explanation from the book C++ Primer:
这很有道理,As in any other declaration, init-statement can define several objects. However, init-statement may be only a single declaration statement. Therefore, all the variables must have the same base type. As one example, we might write a loop to duplicate the elements of a
vector
on the end as follows:
// remember the size of v and stop when we get to the original last element for (decltype(v.size()) i = 0, sz = v.size(); i != sz; ++i) v.push_back(v[i]);
In this loop we define both the index,
i
, and the loop control,sz
, in init-statement.
for
循环的语法是:
C++11 §6.5.3 The for statement [stmt.for]
The
for
statementfor ( for-init-statement ; condition opt ; expression opt ) statement
for-init-statement
是一个语句。声明两种不同类型的变量将使其至少成为两个语句。
如果你想在for循环中使用两个不同类型的变量,其中一个必须在for循环外部声明。你可以通过将循环括在一组大括号内来强制限定第二个变量的范围:
vector<int> v;
{
int i = 0;
for(vector<int>::iterator vi = n.begin(); vi != n.end(); ++vi, ++i) { /* DO STUFF */ }
} //i's scope ends here.
为什么这不被允许?
C++的古怪声明语法不允许在同一声明语句中声明不相关的对象;而一个`for`循环的初始化器只允许一个声明语句。
我想定义两个新的计数器,都是`vi`和索引`i`。
如果您不介意污染周围的块,则可以在循环外声明一个或两个变量。否则,您可以将它们放在结构体中:
for (struct {vector<int>::iterator vi; int i;} x = {n.begin(), 0};
x.vi != n.end();
++x.vi, ++x.i) {}
std::vector<int> v;
{
std::vector<int>::iterator it = n.begin(), end = n.end();
int i = 0;
for ( ; it != end; ++it, ++i)
{}
}
for ( int i = 0, j = 10 ; ... )
int a=1, b=2, c=3, i=0; // comma acts as separator in this line, not as an operator
另外,为什么不这样做呢?
vector<int> v;
vector<int>::iterator vi = n.begin();
int i = 0;
for(; vi != n.end(); ++vi, ++i)
{
}
for(T a=x, b=y, c=z; ...)
, 无法确定具体原因。 - juanchopanza