在for循环中声明多个新计数器

4
请提供需要翻译的内容。
vector<int> v;
for(vector<int>::iterator vi = n.begin(), int i = 0;
    vi != n.end();
    ++vi, ++i){}

为什么不允许这样做呢?我想要定义两个新的计数器,一个是“vi”,另一个是索引“i”。


标准禁止这样做。 - Luchian Grigore
优秀的回答,Luchian。你能再详细解释一下吗? - Henry Henrinson
5
您可以声明同一类型的多个对象,但不能声明不同类型的对象。允许的语法是 for(T a=x, b=y, c=z; ...), 无法确定具体原因。 - juanchopanza
一个相关的(重复?)主题可以在 https://dev59.com/EGoy5IYBdhLWcg3wFqJT 找到。无论如何,您当然可以在循环之前声明一个或两个计数器,并且它将起作用。但是,从保持变量局部化到循环的角度来看,这并不令人满意。 - Roland Sarrazin
你是想知道解决方法还是只是想了解为什么这不被允许? - jrok
显示剩余3条评论
6个回答

4

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 statement

for ( for-init-statement ; condition opt ; expression opt ) statement

for-init-statement 是一个语句。声明两种不同类型的变量将使其至少成为两个语句。


2

如果你想在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.

"在其他地方可能 不能 使用" - Lightness Races in Orbit

2

为什么这不被允许?

C++的古怪声明语法不允许在同一声明语句中声明不相关的对象;而一个`for`循环的初始化器只允许一个声明语句。

我想定义两个新的计数器,都是`vi`和索引`i`。

如果您不介意污染周围的块,则可以在循环外声明一个或两个变量。否则,您可以将它们放在结构体中:

for (struct {vector<int>::iterator vi; int i;} x = {n.begin(), 0}; 
     x.vi != n.end();
     ++x.vi, ++x.i) {}

2
答案是“实际上除了语法要求外没有任何原因”。虽然我可以想象,如果允许这样做,代码可能会变得非常复杂,所以不支持将其添加到语言中是一个很好的理由。您可以创建自己的作用域来限定它:
std::vector<int> v;
{
   std::vector<int>::iterator it = n.begin(), end = n.end();
   int i = 0;

   for ( ; it != end; ++it, ++i)
   {}
}

1
你只能编写一个声明语句,但它可以定义多个变量,例如:
for ( int i = 0, j = 10 ; ... )

0
看一下逗号运算符维基百科页面会有所帮助,特别是第一个例子。
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)
{
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接