for(表达式 1; 表达式 2; 表达式 3){
//循环体
}
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
int main() {
char arc[] = "http://c.biancheng.net/cplus/11/";
int i;
//for循环遍历普通数组
for (i = 0; i < strlen(arc); i++) {
cout << arc[i];
}
cout << endl;
vector<char>myvector(arc,arc+23);
vector<char>::iterator iter;
//for循环遍历 vector 容器
for (iter = myvector.begin(); iter != myvector.end(); ++iter) {
cout << *iter;
}
return 0;
}
程序执行结果为:
http://c.biancheng.net/cplus/11/
http://c.biancheng.net/
此示例中,vector 为 STL 标准库提供的序列式容器,关于该容器的具体用法,可阅读《C++ STL vector容器详解》一节,这里不再做重复赘述。
for (declaration : expression){
//循环体
}
#include <iostream>
#include <vector>
using namespace std;
int main() {
char arc[] = "http://c.biancheng.net/cplus/11/";
//for循环遍历普通数组
for (char ch : arc) {
cout << ch;
}
cout << '!' << endl;
vector<char>myvector(arc, arc + 23);
//for循环遍历 vector 容器
for (auto ch : myvector) {
cout << ch;
}
cout << '!';
return 0;
}
程序执行结果为:
http://c.biancheng.net/cplus/11/ !
http://c.biancheng.net/!
{ }大括号初始化的列表,比如:
#include <iostream>
using namespace std;
int main() {
for (int num : {1, 2, 3, 4, 5}) {
cout << num << " ";
}
return 0;
}
程序执行结果为:
1 2 3 4 5
#include <iostream>
#include <vector>
using namespace std;
int main() {
char arc[] = "abcde";
vector<char>myvector(arc, arc + 5);
//for循环遍历并修改容器中各个字符的值
for (auto &ch : myvector) {
ch++;
}
//for循环遍历输出容器中各个字符
for (auto ch : myvector) {
cout << ch;
}
return 0;
}
程序执行结果为:
bcdef
此程序中先后使用了 2 个新语法格式的 for 循环,其中前者用于修改 myvector 容器中各个元素的值,后者用于输出修改后的 myvector 容器中的各个元素。const &(常引用)形式的变量(避免了底层复制变量的过程,效率更高),也可以定义普通变量。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有