具有多个变量初始化的 C++ for 循环结构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8783896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:06:22  来源:igfitidea点击:

C++ for-loop structure with multiple variable initialization

c++for-loop

提问by jdphenix

On the 2nd for-loop, I get the following error from gcc:

在第二个 for 循环中,我从 gcc 收到以下错误:

error: expected unqualified-id before 'int'

I'm not sure what I'm missing. I've looked over documentation for how a for-loop should look and I'm still confused. What's wrong here?

我不确定我错过了什么。我查看了有关 for 循环外观的文档,但我仍然感到困惑。这里有什么问题?

#include <iostream>
#include <vector>

int main() { 
std::vector<int> values; 

for (int i = 0; i < 20; i++) { 
  values.push_back(i); 
}   

std::cout << "Reading values from 'std::vector values'" << std::endl;
for (int i = 0, int col = 0; i < values.size(); i++, col++) {
  if (col > 10) { std::cout << std::endl; col == 0; }
  std::endl << values[i] << ' ';
  }
}

回答by jweyrich

Try without the intbefore col.

尝试没有intbefore col

for (int i = 0, col = 0; i < values.size(); i++, col++)

for (int i = 0, col = 0; i < values.size(); i++, col++)

回答by Jerry Coffin

Others have already told you how to fix the problem you've noticed. On a rather different note, in this:

其他人已经告诉您如何解决您注意到的问题。在一个相当不同的注释中,在此:

if (col > 10) { std::cout << std::endl; col == 0; }

It seems nearly certain that the last statement here: col==0;is really intended to be col=0;.

几乎可以肯定,这里的最后一个语句:col==0;真的打算是col=0;.

回答by Chethan Ravindranath

This should fix it

这应该解决它

for (int i = 0, col = 0; i < values.size(); i++, col++) {
  if (col > 10) { std::cout << std::endl; col == 0; }
  std::endl << values[i] << ' ';
  }
}

A variable definition goes like this

一个变量定义是这样的

datatype variable_name[=init_value][,variable_name[=init_value]]*;

数据类型 variable_name[=init_value][,variable_name[=init_value]]*;

回答by Kalpesh Patel

Don't declare int after comma use,

不要在逗号使用后声明 int,

for (int i = 0,col = 0; i < values.size(); i++, col++) {
  if (col > 10) { std::cout << std::endl; col == 0; }
  std::endl << values[i] << ' ';
  }
}

回答by def

This is akin to a regular multiple variables declaration/initialization in one line using a comma operator. You can do this:

这类似于使用逗号运算符在一行中进行常规的多变量声明/初始化。你可以这样做:

int a = 1, b = 2;

declaring 2 ints. But not this:

声明 2 个整数。但不是这个:

int a = 1, int b = 2;   //ERROR