VC2010 lambda sample //VC2010 lambda sample // remove_if list<int> numList; for(int i = 10; i < 90; i += 10) numList.push_back(i); cout << "before remove: "; std::copy(numList.begin(), numList.end(), ostream_iterator<int>(cout, ","));cout << endl; numList.remove_if([](int n) { return n < 30; }); cout << "after remove: "; std::copy(numList.begin(), numList.end(), ostream_iterator<int>(cout, ","));cout << endl; /* struct foo { foo(int val):_val(val) { cout << "constructing " << _val << endl;} ~foo(){cout << "destructing " << _val << endl;} int _val; }; */ // work with pointer collections list<foo*> objList; for(int i = 1; i < 10; ++i) objList.push_back(new foo(i)); // sort objList.sort([](foo *x, foo *y) { return x->_val > y->_val; } ); // print for_each(objList.begin(), objList.end(), [](foo *p){ cout << p->_val << ",";}); cout << endl; // find_if: stateful lambdas, capture list [var] int key = 2; auto it = find_if(objList.begin(), objList.end(), [key](foo *p){ return p->_val == key; }); if(objList.end() != it) { cout << "Locate " << key << " at pos: " << std::distance(objList.begin(), it) << endl; } /* the above code section is equivalent to: class LambdaFunctor { public: LambdaFunctor(int key) : _key(key) {} bool operator()(foo *p) const { p->_val == _key ; } private: int _key; }; ...... ...... auto it = find_if(objList.begin(), objList.end(), LambdaFunctor(key)); use: [=](foo *p){ ... }) to capture all local variables */ // clean up for_each(objList.begin(), objList.end(), [](foo *p){ delete p;}); // specific lambda return type list<int> intList; for(int i = 1; i <= 5; ++i) intList.push_back(i); vector<double> ret; transform(intList.begin(), intList.end(), back_inserter(ret), //[](int n)->double { return n * 1.0 / 2; } ); [](int n) { return n * 1.0 / 2; } ); std::copy(ret.begin(), ret.end(), ostream_iterator<double>(cout, ",")); cout << endl; // modify lambda parameters for_each(intList.begin(), intList.end(), [](int &val) { if (val % 2 == 0) val = val+100;} ); std::copy(intList.begin(), intList.end(), ostream_iterator<double>(cout, ",")); cout << endl; // auto isEven = [](const int n)->bool { return n % 2 == 0; }; // modify external variable vector<int> data; int cnt = 0; generate_n(back_inserter(data), 10, [&]() { return cnt++; }); std::copy(data.begin(), data.end(), ostream_iterator<double>(cout, ",")); cout << endl;