前言
C++11這次的更新帶來了令很多C++程序員期待已久的for range循環,每次看到javascript, lua里的for range,心想要是C++能有多好,心里別提多酸了。這次C++11不負眾望,再也不用羡慕別家人的for range了。
使用場景
ex1:遍歷字符串
1 std::string str = “hello, world”; 2 for(auto ch : str) { 3 std::cout << ch << std::endl; 4 }
遍歷str,輸出每個字符,同時用上auto,簡直是如虎添翼。
ex2:遍歷數組
1 int arr[] = {1, 2, 3, 4}; 2 for(auto i : arr) { 3 std::cout<< i << std::endl; 4 }
不用知道數組容器的大小,即可方便的遍歷數組。
ex3:遍歷stl 容器
1 std::vector<std::string> str_vec = {“i”, “like”, "google”}; 2 for(auto& it : str_vec) { 3 it = “c++”; 4 }
在這段程序中,可以返回引用值,通過引用可以修改容器內容。然后用到了初始化列表,在下一篇文章中,將會介紹。
ex4:遍歷stl map
1 std::map<int, std::string> hash_map = {{1, “c++”}, {2, “java”}, {3, “python”}}; 2 for(auto it : hash_map) { 3 std::cout << it.first << “\t” << it.second << std::endl; 4 }
遍歷map返回的是pair變量,不是迭代器。
后記
for range 很簡單,但是為遍歷容器提供了很大的便利,再也不用寫那么長的for循環了。同時也印證我這邊文章說的,C++是變的復雜了,但同時它變的更好了。它提供的特性你不用也沒關系,但如果你一直在使用C++,或者作為合格的程序員,保持學習是亘古不變的。何不花一點時間學習一下C++新特性,不僅提高效率,並且使得自己的代碼更加優美,何樂而不為呢?
原文:http://blog.csdn.net/hackmind/article/details/24271949
參考:https://www.cnblogs.com/jiayayao/p/6138974.html
https://www.cnblogs.com/pzhfei/archive/2013/03/02/CPP_new_feature.html
http://blog.jobbole.com/44015/