【c++11】 lamda表達式

1.標準樣式
[](CString itUrl)->bool {        
        
    }

例子:
不帶參數:
auto fun_helloworld = []()->void{
  std::cout << "hello world" << std::endl;
};

fun_helloworld();

帶一個參數:
auto fun_helloworld = [](std::string aa)->void{
  std::cout << aa << std::endl;
};

fun_helloworld("hello world");


2.[]中幾個值介紹
auto findUrlFun = [=](CString itUrl)->bool {        
        auto itUrlOrigin = GetOriginImageFileUrl(itUrl.GetBuffer());
        return itUrlOrigin.CompareNoCase(urlOrigin) == 0 ? true : false;
    };

(1)[],什麼都不傳

for (int i=0; i<10; ++i)
{
    auto fun_helloworld = [](std::string aa)->void {
        std::cout <<  aa << std::endl;
    };

    fun_helloworld("haha");
}


(2)[]中傳外部變量,如this
例子:
for (int i=0; i<10; ++i)
{
    auto fun_helloworld3 = [i](std::string aa)->void {
        std::cout <<  i << "---" << aa << std::endl;
    };

    fun_helloworld3("haha");
}

(3)[=],"="是值傳遞即只能使用外部變量,不能改變值
for (int i=0; i<10; ++i)
{
    auto fun_helloworld3 = [=](std::string aa)->void {
        std::cout <<  i << "---" << aa << std::endl;
    };

    fun_helloworld3("haha");
}

(4)[&],"&"是引用傳遞,即可以在內部改變外部變量
for (int i=0; i<10; ++i)
{
    auto fun_helloworld3 = [&](std::string aa)->void {
        std::cout <<  i << "---" << aa << std::endl;
        if (i == 9)
        {
            i = 0;
        }
    };

    fun_helloworld3("haha");
}


[]中現在經常看到過this,&,=
說明:=意思是值傳遞,只能使用外部變量,不能改變
&是引用傳遞,即可以在內部改變外部變量

 

 

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