C++11之for迴圈的新用法 for(:)語句
阿新 • • 發佈:2018-12-27
轉載自:https://www.cnblogs.com/jiayayao/p/6138974.html
C++使用如下方法遍歷一個容器:
#include "stdafx.h" #include<iostream> #include<vector> int main() { std::vector<int> arr; arr.push_back(1); arr.push_back(2); for (auto it = arr.begin(); it != arr.end(); it++) { std::cout << *it << std::endl; } return 0; }
其中auto用到了C++11的型別推導。同時我們也可以使用std::for_each完成同樣的功能:
#include "stdafx.h" #include<algorithm> #include<iostream> #include<vector> void func(int n) { std::cout << n << std::endl; } int main() { std::vector<int> arr; arr.push_back(1); arr.push_back(2); std::for_each(arr.begin(), arr.end(), func); return 0; }
現在C++11的for迴圈有了一種新的用法:
#include "stdafx.h"
#include<iostream>
#include<vector>
int main()
{
std::vector<int> arr;
arr.push_back(1);
arr.push_back(2);
for (auto n : arr)
{
std::cout << n << std::endl;
}
return 0;
}
上述方式是隻讀,如果需要修改arr裡邊的值,可以使用for(auto& n:arr),for迴圈的這種使用方式的內在實現實際上還是藉助迭代器的,所以如果在迴圈的過程中對arr進行了增加和刪除操作,那麼程式將對出現意想不到的錯誤。
其實這種用法在其他高階語言裡早有實現,如php,Java,甚至是對C++進行封裝的Qt,foreach也是有的。