auto表示挨个遍历元素
#include <iostream>
#include<vector>
#include<map>
using namespace std;
int main()
{
int array[] = {1, 2, 3, 4, 5};
for(auto e : array)
cout << e << " ";
cout<<endl;
string str = "hello world";
for(auto ch : str)
cout << ch <<" ";
cout<<endl;
vector<int> m_v = {1, 2, 3, 4};
for(auto e : m_v)
cout << e <<" ";
cout<<endl;
map<int,string> m = {{1, "abc"}, {2, "bca"}, {3, "cab"}};
for(auto e : m)
cout <<e.first<<" "<< e.second<<" ";
cout<<endl;
return 0;
}
输出如下:
1 2 3 4 5
h e l l o w o r l d
1 2 3 4
1 abc 2 bca 3 cab
for(auto &i:s)和for(auto i:s)的区别
前者不改变s的值,后者改变s的值(引用)
#include<iostream>
using namespace std;
int main()
{
string s("hello world");
for(auto c:s)
c='t';
cout<<s<<endl;//结果为hello world
for(auto &c:s)
c='t';
cout<<s<<endl; //结果为ttttttttttt
}
输出:
hello world
ttttttttttt