for循环遍历一个数组、string类、vector类等
老写法:
#include
#include
#include
using namespace std;
int main()
{int a[10]={1,2,3,4,5,6,7,8,9};string b("abcdefg");vector<int> c(5);c[1]=1,c[2]=2,c[3]=3,c[4]=4;int i;for(i=0;i<10;i++)cout<<a[i]<<' ';cout<<endl;for(i=0;i<b.size();i++)cout<<b[i]<<' ';cout<<endl;for(i=0;i<c.size();i++)cout<<c[i]<<' ';cout<<endl;
}
运行结果:
1 2 3 4 5 6 7 8 9 0
a b c d e f g
0 1 2 3 4
新用法:
#include
#include
#include
using namespace std;
int main()
{int a[10]={1,2,3,4,5,6,7,8,9};string b("abcdefg");vector<int> c(5);c[1]=1,c[2]=2,c[3]=3,c[4]=4;for(int i : a)cout<<i<<' ';cout<<endl;for(char i : b)cout<<i<<' ';cout<<endl;for(int i : c)cout<<i<<' ';cout<<endl;
}
运行结果:
1 2 3 4 5 6 7 8 9 0
a b c d e f g
0 1 2 3 4
那么问题来了,这个新用法有什么用呢,其实这个新用法在STL里是有了很大的优化的,例如遍历map,set等容器时,往往是要使用迭代器实现的,而有了for循环新用法之后便可以用for循环去代替迭代器了,为写程序带来很大的便利。
看例子:
#include
#include
#include
using namespace std;
int main()
{cout<<"map.text"<<endl;map<int,int> e;e[1]=3;e[8]=5;for(auto d : e){cout<<d.first<<' '<<d.second<<endl;}cout<<"set.text"<<endl;set<int> f;f.insert(5);f.insert(7);for(int d : f){cout<<d<<' ';}
}
运行结果:
map.text
1 3
8 5
set.text
5 7