C++中的遍历循环
1.下标+[ ]
举例:
int main()
{
string s1("hello world");
for(size_t i=0;i<s1.size();i++)
{
s1[i]++;
}
//打印
for(size_t i=0;i<s1.size();i++)
{
cout<<s1[i]<<" ";
}
cout<<endl;
通过以上的代码可以看出来c++中的遍历比C语言中的遍历更加方便,因为我使用了string类中的一些函数如:size()计算当前数组的大小,不再需要c语言中的sizeof。
2.迭代器
举例:
int main()
{
string s1("hello world");
string::iterator it1=s1.begin();
while(it1!=s1.end())
{
++it1;
}
while(it1!=s1.end())
{
cout<<*it1<<""
}
cout<<endl;
}
使用迭代器去遍历是比较推荐的一种方式,因为这种方式比较通用,迭代器本质和指针有些类型,但也有不同之处,这以后再说。
3.范围for
举例:
int main()
{
string s1("hello world");
for(auto ch : s1)
{
cout<<ch<<" ";
}
cout<<endl;
}
对比以上的代码是不是感觉范围for的代码更少,这正是因为auto的作用,auto可以自动通过右边的值推到左边的值是什么类型。其实范围for的本质还是迭代器。