它是Range-based for loop,C++11 引入的新语法。
使用举例
代码:
for(auto x : v)
{
cout << x << " ";
}
等价于
for(auto it = v.begin(); it != v.end(); ++it)
{
int x = *it;
cout << x << " ";
}
适用于所有支持迭代器的数据结构。
一、数组
int N[5] = {1,2,3,4,5};
for(int x : N)
{
cout << x << " ";
}
输出
1 2 3 4 5
二、vector
vector<int> v = {1,2,3};
for(int x : v)
{
cout << x << " ";
}
输出
1 2 3
三、string
string s = "noip";
for(char x : s)
{
cout << x << " ";
}
输出
n o i p
四、set
set<int> s = {3,1,4,2};
for(int x : s)
{
cout << x << " ";
}
输出
1 2 3 4//因为set会内部排序
五、map
map<int,int> mp;
mp[1] = 999;
mp[2] = 777;
for(auto p : mp)
{
cout << p.first << " "<< p.second << endl;
}
输出
1 999
2 777
六、自定义类
只要自定义的类能实现:begin();end();
就能使用它。
class K
{
public:
int N[3]={1,2,3};
int* begin()
{
return N;
}
int* end()
{
return N+3;
}
};
K sp;
for(int x : sp)
{
cout << x << " ";
}
输出
1 2 3

3225

被折叠的 条评论
为什么被折叠?



