for循环 |
for(init; test; update) { // 初始化; 测试条件; 更新(步长)
statement;
}
for(int i = 0; i < 10; ++i) {
cout << i << endl;
}
for(int i = 0; i <= 10; i += 2) cout << i << endl;
for(int i = vi.size()-1; i >= 0; --i) cout << vi[i] << endl;
- C++赋值表达式的值为左侧成员的值
- for循环中的三条表达式都可省略 – for( ; ; )是合法的
- for循环中的初始化条件可以声明变量
递增(++) 和 递减(–)
- 前缀++ – 先++再以当前值计算表达式 – ++a
- 后缀++ – 先以当前值广告牌表达式, 再++ – a++
- 同一条语句尽量不要使用多个++, 否则在不同的系统上将会有不同的结果,
- 如 x = 2 * x++ * (3 - ++x); 在我的系统上输出为 0
- 前缀++效率高一些 – 后缀++的实现需要复制一个副本后++再返回副本
int a = 5; int b = ++a; // b = 6, a = 6 int c = a++; // c = 5, a = 6
- 逗号表达式的值为右边的值
- C风格字符串的比较 – strcmp(a, b)
- 相等 – 值为9
- a 在 b 前面 – 值 < 0
- a 在 b 后面 – 值 > 0
基于范围的for循环(C十十11) |
int a[5] = {1, 2, 3, 4, 5};
for(int i : a) cout << i << endl;
若要修改数据的话 – 使用引用
for(int& i : a) i += 1;
也可结合初始化表
for(int i : {1, 2, 3}) cout << i << endl;
while循环 |
init; // 初始条件
while (test) { // 测试条件
statement;
update; // 更新(步长)
}
int i = 0;
while (i < 5) {
cout << i << endl;
++i;
}
使用while 配合 < ctime > 编写延迟循环
#include <iostream> #include <ctime> using namespace std; int main() { float secs; cin >> secs; clock_t delay = secs * CLOCKS_PER_SEC; // 延迟时间 clock_t start = clock(); // 开始时间 cout << start << endl; while (clock() - start < delay); // 当前时间 - 开始时间 < 延迟时间时 等待 cout << "done\n"; return 0; }
类型别名
- 使用define
- 使用typedef
#define LL long long typedef long long LL;
do while循环 |
init;
do {
statement;
update;
} while (test);
int i = 0;
do {
cout << i <<< endl;
++i;
} while (i < 5);
- 出口条件循环
- 先执行循环体, 再判定测试表达式
循环和文本输入 |
哨兵字符
char ch; cin.get(ch); // 不用 cin>>ch 是为了读取空格 while(ch != '#') { cout << ch; cin.get(ch); }
检测文件尾(EOF)
- 使用cin.eof() 或 cin.fail()
char ch; cin.get(ch); while(cin.fail() == false) { cout << ch; cin.get(ch); }
cin 本身可转为bool值
char ch; while(cin.get(ch)) { cout << ch; }
另一个版本的cin.get() – 不带参数 返回一个字符
int ch; // 有的char是无符号的 EOF值为-1 ch = cin.get(); while(ch != EOF) { cout.put(char(ch)); // 输出一个字符 ch = cin.get(); }
嵌套循环和二维数组 |
int a[2][3] = { // 二行 三列
{1, 2, 3},
{4, 5, 6}
};
// 二层for循环输出
for(int i = 0; i < 2; ++i) {
for(int j = 0; j < 3; ++j) cout << a[i][j] << " ";
cout << endl;
}