天天看點

lambda與bind函數的使用

#include <iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<numeric>
#include<functional>


using namespace std;
using namespace std::placeholders;
bool isShorter(const int &a, const int &b)
{
    return a < b;
}


void cNum(const int &c)
{
    cout << c << " ";
}

int main()
{
    vector<int> vec {1, 2, 46, 25, 36, 78, 9, 8};

    //使用lambda排序vec中的元素
    stable_sort(vec.begin(), vec.end(), [] (const int &a, const int &b) { return a < b; });

    //使用bind函數排序vec中的元素
    stable_sort(vec.begin(), vec.end(), bind(isShorter, _1, _2));

    //列印vec的内容
    for (auto it = vec.begin(); it != vec.end(); it++)
    {
        cout << *it  << " ";
    }

    cout << endl;

     //使用lambda列印vec
    for_each(vec.begin(), vec.end(), [] (const int &fc) { cout << fc << " "; });
        cout << endl;

    //使用bind列印vec
    for_each(vec.begin(), vec.end(), bind(cNum, _1));

    
    return 0;
}