C++循环,loops!!!!!!!!
1.常用的循环for,while
2.首先我们来谈谈for循环,大家都知道,下面这段代码说明打印helloword 5次,在for循环的头部规定好初始条件,循环条件即可
#include <iostream> using namespace std; int main() { for(int i = 0; i < 5; i++) { cout << "Hello World!" << endl; } return 0; }
但是用for循环只有这一种写法吗?当然不是,你还可以什么都不在for头部写,比如下面这样
#include <iostream> using namespace std; int main() { int i = 1; bool flag = true; for(;flag;) { cout << "Hello World!" << endl; i++; if(i > 5) flag = false; } return 0; }
还有把迭代器融入for循环的写法
vector<string> strings; strings.push_back("happy"); strings.push_back("sad"); for(auto it = strings.begin();it != strings.end();it++) { cout << *it << endl; }
3.接下来while
#include <iostream> using namespace std; int main() { int i = 0; while(i < 5) { cout << "Hello World!" << endl; i++; } return 0; }
while还有另一种写法,叫do while,是指这个循环无论如何都会执行一次,这就是这段代码的重点
#include <iostream> using namespace std; int main() { bool flag = false; int i = 0; do { cout << "Hello World!" << endl; i++; } while(flag); return 0; }
4.那我们什么时候用for什么时候用while呢?
答案是:这两种方法没有实质性区别,你选择用哪个更像是一种习惯或风格,而不是必须的规矩
但是有一种习惯约定:如果你已经有一个存在的确定条件,那就用while;如果你有确定的循环次数,那就用for
所以从上面这两个例子我们看到for更强调数字及while写法的简洁性