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 }

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM