C++11 遍歷容器方法簡記

簡略記錄使用 C++11 特性對 vector 容器進行遍歷,用到了多個方法,對於方法的取捨見仁見智

包括但不限於以下方法:

- 普通迭代器方法

- auto關鍵字識別迭代器方法

- auto關鍵字範圍遍歷方法

- for_each加函數遍歷方法

- for_each與lamanda表達式組合方法

/*================================================================
*   Copyright (C) 2018 Renleilei. All rights reserved.
*   
*   文件名稱:030_auto.cpp
*   創 建 者:Renleilei ([email protected])
*   創建日期:2018年02月02日
*   描    述:
*   版    本: Version 1.00
*   編譯方法: g++ -o main 030_auto.cpp -std=c++11 -g -Wall -O3
================================================================*/


#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

void myPrint(int i);

int main()
{
    std::vector<int> vec_01;
    vec_01.push_back(1);
    vec_01.push_back(2);
    vec_01.push_back(3);
    vec_01.push_back(4);

    // use normal iterator 使用普通迭代器遍歷vector
    cout << "With iterator: " << endl;
    std::vector<int>::iterator it = vec_01.begin();
    for(it; it != vec_01.end(); ++it){ cout << *it << endl; }

    // use auto key word 使用auto關鍵字遍歷vector(本質上使用了auto自動識別爲迭代器的類型)
    cout << "With normal auto iterator: " << endl;
    for(auto ivec_01 = vec_01.begin(); ivec_01 != vec_01.end(); ++ivec_01){ cout << *ivec_01 <<endl; }

    // use auto key word with range 使用auto關鍵字對vector範圍內遍歷
    cout << "With auto range: " << endl;
    for(auto  ivec : vec_01){ cout << ivec << endl; }

// use for_each key word 使用for_each算法對vector進行遍歷, 調用函數myPrint()
    cout << "With Normal for_each: " << endl;
    for_each(vec_01.begin(), vec_01.end(), myPrint);

    // use lamanda and for_each 使用for_each加lamanda表達式組合對vector進行遍歷
    cout << "With Lamanda express: " << endl;
    for_each(vec_01.begin(), vec_01.end(), [](int i){ cout << i << endl;});
    return 0;
}

void myPrint(int i)
{
    cout << i << endl;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章