隨着C++11標準的出現,C++標準添加了許多有用的特性,C++代碼的寫法也有比較多的變化。c++
vector是常常要使用到的std組件,對於vector的遍歷,本文羅列了若干種寫法。函數
(注:本文中代碼爲C++11的代碼,須要在較新的編譯器中編譯運行)學習
假設有這樣的一個vector:get
vector<int> valList = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };原型
須要輸出這個vector中的每一個元素,原型以下:編譯器
複製代碼it
void ShowVec(const vector<int>& valList)for循環
{編譯
}社區
int main(int argc, char* argv[])
{
vector<int> valList = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ShowVec(valList);
return 0;
}
複製代碼
下面就開始咱們的茴香豆的N種寫法吧 !
方法零,對C念念不捨的童鞋們習慣的寫法:(c++ 98/03 ,c++ 11 通用)
複製代碼
void ShowVec(const vector<int>& valList)
{
int count = valList.size();
for (int i = 0; i < count;i++)
{
cout << valList[i] << endl;
}
}
複製代碼
方法一,你們喜聞樂見的for循環迭代器輸出:(c++ 98/03 ,c++ 11 通用)
複製代碼
void ShowVec(const vector<int>& valList)
{
for (vector<int>::const_iterator iter = valList.cbegin(); iter != valList.cend(); iter++)
{
cout << (*iter) << endl;
}
}
複製代碼
方法二,與方法一差很少,不過能少打幾個字:(僅c++ 11 可用)
複製代碼
void ShowVec(const vector<int>& valList)
{
for (auto iter = valList.cbegin(); iter != valList.cend(); iter++)
{
cout << (*iter) << endl;
}
}
複製代碼
方法三,for_each加函數:(c++ 98/03 ,c++ 11 通用)
複製代碼
template<typename T>
void printer(const T& val)
{
cout << val << endl;
}
void ShowVec(const vector<int>& valList)
{
for_each(valList.cbegin(), valList.cend(), printer<int>);
}
複製代碼
方法四,for_each加仿函數:(c++ 98/03 ,c++ 11 通用)
複製代碼
template<typename T>
struct functor
{
void operator()(const T& obj)
{
cout << obj << endl;
}
};
void ShowVec(const vector<int>& valList)
{
for_each(valList.cbegin(), valList.cend(), functor<int>());
}
複製代碼
方法五,for_each加Lambda函數:(僅c++ 11 可用)
void ShowVec(const vector<int>& valList)
{
for_each(valList.cbegin(), valList.cend(), [](const int& val)->void{cout << val << endl; });
}
方法六,for區間遍歷:(僅c++ 11 可用)
for (auto val : valList)
{
cout << val << endl;
}
etc.
本文純屬無聊所寫,期待更多蛋疼的方法!
最後:
C++11相比C++98/03仍是更新了挺多東西的,目前g++最新版已徹底支持C++11標準,這意味着開源社區的新的project必然將遷移到最新的C++11標準上,平時參與/閱讀/參考開源代碼的童鞋們須要學習了。