C++ for循环与迭代器

1.基本的for循环

1 std::vector<int> arr;
2 ...
3 for(std::vector<int>::iterator it=arr.begin();it!=arr.end();it++){
4 ...       
5 }

2.使用auto关键字

1 std::vector<int> arr;
2 ...
3 for(auto it = arr.begin();it != arr.end();it++){
4 ...
5 }

3.使用c++11 for循环新特性

1 std::vector<int> arr;
2 ...
//注意此处的 n 得类型为 arr容器的value_type,即auto自动推导出vector中为int类型,n为arr中的值。
3 for(auto n : arr){ 4 ...//如果上面arr类型为std::map<std::string,int>,获取arr的string值n.first,获取arr的int值n.second。
5 }

注:如需转载请注明出处。

------------ ----------------https://www.gnsoft.ltd------------------- ------------
原文地址:https://www.cnblogs.com/guozht/p/7641934.html