关于auto的一些使用方法 :
- for(auto x : arr) 遍历方式, x只是将arr里的元素复制下来,改变x不会改变arr的元素
- for(auto &x : arr) x是将arr元素的地址拿出来,改变x会改变arr的元素
1 数组
int a[] = {1,2,3,4,5,6};
for(auto item : a)
cout << item << endl;
等价于
for(int i = 0; i < 6; i++)
cout << a[i] << endl;
2、字符串
string str = "hello world";
for(auto ch : str)
cout << ch <<endl;
等价于
for(int i = 0; i <str.size(); i++)
cout << str[i] <<endl;
3、vector
vector<int> m_v = {1, 2, 3, 4};
for(auto e : m_v)
cout << e <<endl;
等价于
for(int i = 0; i < m_v.size(); i++)
cout << v[i] <<endl;
4、map
map<int,string> m = {{1, "abc"}, {2, "bca"}};
for(auto e : m)
cout << e.first << " " << e.second<<endl;
等价于
map<int, string>::iterator it = m.begin();
for(;it != m.end(); it++)
cout << it->first << " " << it->second<<endl;
—— 本文来自火龙信奥(义乌睿码科技):义乌青少年信息学奥赛与编程教育平台,专注 CSP-J/S、NOIP、GESP 竞赛培训,线上线下融合教学,助力编程升学。网址:hlcoding.com