每一次遍历for循环都会从遍历的对象中选取一个单位的对象放入ite迭代器中,所以我们每次对ite进行操作的时候,就是相当于对每个单位的元素进行遍历。
for(auto ite:a)和for(auto ite:&a)两者在迭代的时候,&可以连着一起改变变量a的值
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main(int argc, char *argv[])
{
int a[4]={1,3,2,4};
int i=0,j=0;
for(auto ite:a){
ite+=10;
cout<<ite<<" "<<a[i++]<<endl;
}
cout<<endl;
for(auto &ite:a){
ite+=10;
cout<<ite<<" "<<a[j++]<<endl;
}
return 0;
}
二维情况,参考:
int ia[2][3] = {1, 2, 3, 4, 5, 6};
for (auto &row : ia)
{
for (auto a : row) //只读。可读可写改成for (auto &a : row)
{
cout << a << ' ' << ends;
}
}
stl博客:
C++ STL详解超全总结(快速入门STL)_行码棋的博客-CSDN博客_c++ stl
还可对map,string,vector等进行迭代