gpt4 book ai didi

c++ - 在 for 循环中声明几个新的计数器

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:10:29 25 4
gpt4 key购买 nike

考虑以下代码:

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

是否有不允许这样做的原因?我希望能够定义 2 个新计数器,vi 和索引 i。

最佳答案

这是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 只是一个语句。声明两种不同类型的变量会使它至少有两个语句。

关于c++ - 在 for 循环中声明几个新的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19497435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com