应用
foreach语句中
#include <time.h> #include <algorithm> using namespace std; void func(int i) { cout<<i<<endl; } int main(int argc, char *argv[]) { list<int> li; srand(time(NULL)); for(int i=0;i <10; i++) { li.push_back(rand()%100); } for_each(li.begin(),li.end(),func); for_each(li.begin(),li.end(),[](int i){cout<<i<<endl;});
//!传函数指针的地方可以用lanbda表达式替代。 return 0; }
sort()/list::sort()
#include <iostream> #include <vector> #include <list> #include <stdlib.h> #include <time.h> #include <algorithm> #include <functional> using namespace std; bool Compare(int i, int j) { return i<j; } int main(int argc, char *argv[]) { vector<int> vi; srand(time(NULL)); for(int i=0;i <10; i++) { vi.push_back(rand()%100); } // sort(vi.begin(),vi.end(),Compare); sort(vi.begin(),vi.end(),[](int x, int y){ return x<y;}); for_each(vi.begin(),vi.end(),[](int i){cout<<i<<endl;}); return 0;
Qt中信号槽机制
#include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { this->setGeometry(600,400,400,200); _dial = new QDial(this); _dial->setRange(0,100); _dial->setGeometry(50,50,100,100); _dial->setAutoFillBackground(true); _pBar = new QProgressBar(this); _pBar->setGeometry(250,40,20,120); _pBar->setMinimum(0); _pBar->setMaximum(100); _pBar->setOrientation(Qt::Vertical); //connect(_dial,SIGNAL(valueChanged(int)), _pBar,SLOT(setValue(int))); //QObject::connect(const QObject *sender,PointerToMemberFunction signal,Functor functor)
connect(_dial,&QDial::valueChanged,[&](int v){_pBar->setValue(v);});
//!可以使用lambda表达式替代槽函数
}
MainWindow::~MainWindow() { }
lambda表达式与仿函数
#include <iostream> using namespace std; class Tax {
public: Tax(float r, float b):_rate(r),_base(b){} float operator()(float money) { return (money-_base)*_rate; } private: float _rate; float _base; };
int main(int argc, char *argv[]) { // Tax high(0.40,30000); // Tax middle(0.25,20000); // Tax low(0.12,10000); // cout<<"大于 3w 的税:"<<high(37500)<<endl; // cout<<"大于 2w 的税:"<<middle(27500)<<endl; float rate = 0.40; float base = 30000; auto high = [&](float money){return (money-base)*rate;}; cout<<"大于 3w 的税:"<<high(37500)<<endl; return 0; }