c++11新標準for循環和lambda表達式

 

1 for

在C++11中for擴展了一個新的用法,相似於c#中的foreach.能夠用來遍歷容器,輸出和關聯容器等。配合另外的c++11新關鍵字auto可以很方便的實現遍歷。用法以下:css

#include <iostream>
 
int main()
{
  std::string myStr = "hello!";
  for(auto ch : myStr)
    std::cout<<ch<<std::endl;
}

上面函數的做用是遍歷 string 而後輸出其每個元素。html

2 lambda表達式

關於lambda表達式在 C++ Lambda表達式用法C++11 lambda表達式解析 這兩篇文章中已經有了比較詳細的介紹了。其完整表達式爲:java

[ capture ] ( params ) mutable exception attribute -> ret { body }

這裏對 capture 進行補充說明一下,上面的第二篇文章將這個翻譯爲捕獲,第一遍看到的時候比較困惑。後來才發現這個其實就是指定了lambda表達式做爲函數對象其構造函數傳遞進來的參數是什麼,只有傳遞進來的參數lambda表達式才能夠使用, 即lambda表達式會生成一個重載了()操做的函數對象,該對象的構造函數參數由[]內參數指定 。其餘的沒有什麼好補充的。能夠在支持c++11標準的編譯器上運行下面代碼感覺一下:python

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
 
class LessFunction
{
public:
    LessFunction(int threshold) :Threshold(threshold) {}
 
    bool operator () (int n)
    {
        return n < Threshold;
    }
private:
    int Threshold;
 
};
 
int main()
{
    //使用普通的函數對象
    std::vector<int> a { 1,2,3,4,5,6,7 };
    LessFunction myFun(5);
    a.erase(std::remove_if(a.begin(), a.end(), myFun), a.end());
    std::cout << "a:" ;
    for (auto i : a)
        std::cout << i << " ";
    std::cout << std::endl;
 
    //使用lambda表達式,以值傳遞的方式將x做爲函數對象的構造函數參數
    std::vector<int> b{ 1,2,3,4,5,6,7 };
    int x = 5;
    b.erase(std::remove_if(b.begin(), b.end(), [x](int n) {return n < x; }), b.end());
    std::cout << "b:" ;
    for (auto i : b)
        std::cout << i << " ";
    std::cout << std::endl;
 
    //保存lambda表達式生成的函數對象
    auto func1 = [](int i) {return i + 4; };
    std::cout << "func1: 6+4=" << func1(6) << std::endl;
 
    //進一步說明lambda表達式生成的是函數對象,用函數對象保存
    std::function<int(int)> func2 = [](int i) {return i + 4; };
    std::cout << "func2: 6+4=" << func2(6) << std::endl;
 
    system("pause");
}

這裏lambda表達式返回類型的值有return語句推導出。只要明確函數對象構造函數的參數和函數調用參數的不一樣,對於lambda表達式的[]和()理解也就更加清晰了。ios

相關文章
相關標籤/搜索