論C++11 中vector的N種遍歷方法


隨着C++11標准的出現,C++標准添加了許多有用的特性,C++代碼的寫法也有比較多的變化。

vector是經常要使用到的std組件,對於vector的遍歷,本文羅列了若干種寫法。

注:本文中代碼為C++11標准的代碼,需要在較新的編譯器中編譯運行

 

假設有這樣的一個vector:(注意,這種列表初始化的方法是c++11中新增語法)

vector<int> valList = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

需要輸出這個vector中的每個元素,測試原型如下:

void ShowVec(const vector<int>& valList)
{
}
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念念不舍的童鞋們習慣的寫法:

void ShowVec(const vector<int>& valList)
{
    int count = valList.size();
    for (int i = 0; i < count;i++)
    {
        cout << valList[i] << endl;
    }
}

 或者

void ShowVec(const vector<int>& valList)
{
    int count = valList.size();
    for (int i = 0; i < count;i++)
    {
        cout << valList.at(i) << endl;
    }
}

 

方法一,大家喜聞樂見的for循環迭代器輸出,(注意,此處使用了C++11中新增的標准庫容器的cbegin函數)

void ShowVec(const vector<int>& valList)
{
    for (vector<int>::const_iterator iter = valList.cbegin(); iter != valList.cend(); iter++)
    {
        cout << (*iter) << endl;
    }
}

或者使用c++新增的語義auto,與上面差不多,不過能少打幾個字:

void ShowVec(const vector<int>& valList)
{
    for (auto iter = valList.cbegin(); iter != valList.cend(); iter++)
    {
        cout << (*iter) << endl;
    }
}

 

方法二,for_each加函數:

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加仿函數:

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函數:(注意:lambda為c++11中新增的語義,實則是一個匿名函數)

void ShowVec(const vector<int>& valList)
{
    for_each(valList.cbegin(), valList.cend(), [](const int& val)->void{cout << val << endl; });
}

 

方法五,for區間遍歷:(注意,for區間遍歷是c++11新增的語法,用於迭代遍歷數據列表)

for (auto val : valList)
{
    cout << val << endl;
}

 

etc.

本文純屬無聊所寫,期待更多蛋疼的方法!

 

最后:

C++11相比C++98/03還是更新了挺多東西的,目前g++最新版已完全支持C++11標准,這意味着開源社區的新的project必然將遷移到最新的C++11標准上,平時參與/閱讀/參考開源代碼的童鞋們需要學習了。

作為C++程序員,我們當然要與時俱進,擁抱C++11!

 

此處推薦一個學習C++11的github鏈接:https://github.com/sib9/cpp1x-study-resource 

 

下面附一個C++11更新列表:

 --------------------------------------------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM