C++ 在范围for循环中有多个语句
我想知道是否可以转换这个表达式C++ 在范围for循环中有多个语句,c++,C++,我想知道是否可以转换这个表达式 vector<Mesh>::iterator vIter; for(int count = 0, vIter = meshList.begin(); vIter < meshList.end(); vIter++, count++) { ... } 有办法做到这一点吗?不,这是不可能的。您所能做的最好工作如下: int count = 0; for(auto &mesh : meshList) { ... ++count
vector<Mesh>::iterator vIter;
for(int count = 0, vIter = meshList.begin(); vIter < meshList.end(); vIter++, count++)
{
...
}
有办法做到这一点吗?不,这是不可能的。您所能做的最好工作如下:
int count = 0;
for(auto &mesh : meshList)
{
...
++count;
}
仅出于完整性的考虑,我只想指出,您可以通过(欺骗和)聚合它们,在For循环的init列表中定义这两个:
for(struct { int count; decltype(meshList)::iterator vIter; } _{0, meshList.begin()} ;
_.vIter < meshList.end(); _.vIter++, _.count++)
{
// ...
}
for(struct{int count;decltype(meshList)::迭代器vIter;}{0,meshList.begin();
_.vIter
但正如你可能已经注意到的那样,它冗长、丑陋,而且完全不值得。中的溶液至少比中的溶液好100倍。否。范围迭代就是这样。必须单独初始化
count
,使用范围迭代,并在循环开始时手动递增count
(初始化count
为小于其起始值的值)。第一个表达式不合法C++
。不能在逗号分隔的初始值设定项中放置两种不同的类型<在for
范围中的code>vIter是一个int
@Galik,出于某种原因,我总是忘记类型必须相同。这似乎是一个逻辑特性(能够初始化多个类型),很难想象为什么它没有这样实现。好的,谢谢。我认为这是一个糟糕的答案
for(struct { int count; decltype(meshList)::iterator vIter; } _{0, meshList.begin()} ;
_.vIter < meshList.end(); _.vIter++, _.count++)
{
// ...
}