1. 程式人生 > 實用技巧 >論C++11 中vector的N種遍歷方法

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

轉載:https://www.cnblogs.com/xylc/p/3653036.html

隨著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;
    }
}

或者

1 2 3 4 5 6 7 8 voidShowVec(constvector<int>& valList) { intcount = valList.size(); for(inti = 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;
}