Range-Based-For
熟悉C++98/03的對於for循環就再瞭解不過了,如果我們要遍歷一個數組,那麼在C++98/03中的實現方式:
int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < 10; i++)
cout << arr[i];
而遍歷容器類的For如下:
std::vector<int> vec {1,2,3,4,5,6,7,8,9,10};
for (std::vector<int>::iterator itr = vec.begin(); itr != vec.end(); itr++)
std::cout << *itr;
不管上面哪一種方法,都必須明確的確定for循環開頭以及結尾條件,而熟悉C#或者python的人都知道在C#和python中存在一種for的使用方法不需要明確給出容器的開始和結束條件,就可以遍歷整個容器,幸運的是C++11中引入了這種方法也就是基於範圍的For(Range-Based-For),用基於範圍的For 改寫上面兩個例子:
std::vector<int> vec {1,2,3,4,5,6,7,8,9,10};
for (auto n :vec)
std::cout << n;
int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (auto n : arr)
std::cout << n;
可以看到改寫後的使用方法簡單了很多,代碼的可讀性提升了一個檔次,但是需要注意的在上述對容器的遍歷是隻讀的,也就是說遍歷的值是不可修改的,看下面例子:
std::vector<int> ve