官术网_书友最值得收藏!

Preparing the value using initialization captures

Another great feature of the Lambda expression coming up in C++14 is its initialization captures. The expression can capture a value of the variable and assign it to the expression's variable. Let's take a look at the following piece of code implementing the initialization captures:

    /* lambda_initialization_captures.cpp */
#include <iostream>

using namespace std;

auto main() -> int
{
cout << "[lambda_initialization_captures.cpp]" << endl;

// Initializing a variable
int a = 5;
cout << "Initial a = " << a << endl;

// Initializing value to lambda using the variable
auto myLambda = [&x = a]() { x += 2; };

// Executing the Lambda
myLambda();

// Displaying a new value of the variable
cout << "New a = " << a << endl;

return 0;
}

As we can see in the preceding code, we have an int variable named a with the value 5. The Lambda expression, myLambda, then captures the a value and executes it in the code. The result is that now the a value will be 7 since it is added by 2. The following output screenshot should appear in our console window when we run the preceding code:

From the preceding snapshot, we see that we can prepare the value to be included in the calculation inside the Lambda expression.

主站蜘蛛池模板: 搜索| 新巴尔虎左旗| 蒲江县| 阜新市| 彝良县| 弋阳县| 嘉义市| 闽侯县| 浮山县| 湟源县| 清丰县| 高清| 台东市| 穆棱市| 枣阳市| 莫力| 托里县| 黄冈市| 峨边| 双流县| 海伦市| 上高县| 伊金霍洛旗| 留坝县| 江阴市| 扬州市| 石河子市| 武山县| 静宁县| 安陆市| 无为县| 奎屯市| 陆河县| 环江| 甘南县| 芜湖市| 平乡县| 彭州市| 浦江县| 宜川县| 邓州市|