STL-C++11のLambda式(上)

4761 ワード

LambdaはC++11から始まり、式または文内で関数の動作を指定する定義式です.
関数動作をオブジェクトとして定義し、predicate(判断式)としてinline実パラメータの形でアルゴリズムに渡すことができます.
eg:
std:transform(coll.begin(), coll.end(), //source
                     coll.begin(),                 //destination
 
 
               
#include 
#include 
#include 
#include "LambdaTest.h"
#include "../../Core/ContainerUtil.h"

using namespace std;

deque<int> coll = { 1, 3, 19, 5, 13, 7, 11, 2, 17 };

cout << "all elements:" << endl;
ContainerUtilint>>::printElements(coll);

int x, y;
cout << "Input x: ";
cin >> x;
cout << endl;
cout << "Input y: ";
cin >> y;
cout << endl;
auto pos = find_if(coll.cbegin(), coll.cend(),  // range
    [=](int i) {                 // search criterion
    return i > x && i < y;
});

cout << "first elem >"<< x <<" and <"<< y <<": " << *pos << endl;

      [](double d) {         //lambda as function object
 
 
 
                       return d*d*d;
                     });
 
簡単な例を見てみましょう.
findFirstInRange.cpp
 
実行結果:
all elements:   1  3  19  5  13  7  11  2  17
Input x: 5
Input y: 18
first elem >5 and <18: 13
 
注意点:
[=]
この記号はlambdaが宣言されたときに有効であるすべての記号がlambda体内に伝達されることを示している.
[&]
この記号はlambdaが宣言されたときに有効であるすべての記号がlambda体内に伝達参照(by reference)の形で伝達されることを示している.
Lambdaの内部で値を変更できます
 
上の例lambdaの等価物
auto pos = find_if(coll.cbegin(), coll.cend(), //range    [=](int i) {                //search criterion    return i > x && i < y;});
それは
1.手書きのループ
 
deque<int>::iterator pos;
for (pos = coll.begin;pos!=coll.end(); ++pos)
{
  if (*pos > x && *pos < y)
  {
     break;
  }
}

 
2.predicate(判断式)
 
bool pred(int I)
{
  return I > x && I < y;
}

...

pos = find_if(coll.begin(), coll.end(), pred);