对于循环
for 循环在 loop body 中执行语句,而循环 condition 为 true。循环之前 initialization statement 只执行一次。每个循环后,执行 iteration execution 部分。
for 循环定义如下:
for (/*initialization statement*/; /*condition*/; /*iteration execution*/)
{
    // body of the loop
}
占位符语句的说明:
- initialization statement:此语句仅在- for循环开始时执行一次。你可以输入一种类型的多个变量的声明,例如- int i = 0, a = 2, b = 3。这些变量仅在循环范围内有效。在循环执行期间隐藏在具有相同名称的循环之前定义的变量。
- condition:此语句在每个循环体执行之前进行评估,如果计算结果为- false则中止循环。
- iteration execution:这个语句在循环体之后执行,在下一个条件评估之前,除非- for循环在体内被中止 (通过- break,- goto,- return或抛出异常)。你可以在- iteration execution部分输入多个语句,例如- a++, b+=10, c=b+a。
一个 for 循环的粗略等价,重写为 while 循环是:
/*initialization*/
while (/*condition*/)
{
    // body of the loop; using 'continue' will skip to increment part below
    /*iteration execution*/
}
使用 for 循环的最常见情况是执行特定次数的语句。例如,请考虑以下事项:
for(int i = 0; i < 10; i++) {
    std::cout << i << std::endl;
}
有效循环还包括:
for(int a = 0, b = 10, c = 20; (a+b+c < 100); c--, b++, a+=c) {
    std::cout << a << " " << b << " " << c << std::endl; 
}
在循环之前隐藏声明变量的示例是:
int i = 99; //i = 99
for(int i = 0; i < 10; i++) { //we declare a new variable i
    //some operations, the value of i ranges from 0 to 9 during loop execution
}
//after the loop is executed, we can access i with value of 99
但是如果你想使用已经声明的变量而不是隐藏它,那么省略声明部分:
int i = 99; //i = 99
for(i = 0; i < 10; i++) { //we are using already declared variable i
    //some operations, the value of i ranges from 0 to 9 during loop execution
}
//after the loop is executed, we can access i with value of 10
笔记:
- 初始化和增量语句可以执行与条件语句无关的操作,或者根本不执行任何操作 - 如果你希望这样做。但出于可读性原因,最佳做法是仅执行与循环直接相关的操作。
- 初始化语句中声明的变量仅在 for循环的范围内可见,并在循环终止时释放。
- 不要忘记在 initialization statement中声明的变量可以在循环期间修改,以及在condition中检查的变量。
从 0 到 10 计数的循环示例:
for (int counter = 0; counter <= 10; ++counter)
{
    std::cout << counter << '\n';
}
// counter is not accessible here (had value 11 at the end)
代码片段的说明:
- int counter = 0将变量- counter初始化为 0.(此变量只能在- for循环内使用。)
- counter <= 10是一个布尔条件,检查- counter是否小于或等于 10.如果是- true,则循环执行。如果是- false,则循环结束。
- ++counter是一个递增操作,它在下一个条件检查之前将- counter的值增加 1。
通过将所有语句留空,可以创建无限循环:
// infinite loop
for (;;)
    std::cout << "Never ending!\n";
与上述相当的 while 循环是:
// infinite loop
while (true)
    std::cout << "Never ending!\n";
但是,仍然可以通过使用语句 break,goto 或 return 或通过抛出异常来保留无限循环。
在不使用 <algorithm> 标头的情况下迭代来自 STL 集合(例如,vector)的所有元素的下一个常见示例是:
std::vector<std::string> names = {"Albert Einstein", "Stephen Hawking", "Michael Ellis"};
for(std::vector<std::string>::iterator it = names.begin(); it != names.end(); ++it) {
    std::cout << *it << std::endl;
}