zoukankan      html  css  js  c++  java
  • C++ 指针函数和lambda

    #include <iostream>
    using namespace std;
    //函数指针,利用函数指针来优化程序
    bool div2(int n)
    {
        return n % 2 == 0;
    }
    
    void printfArray(int a[], size_t len, bool (*ptr)(int))
    {
        for(size_t i = 0;i < len;++i)
        {
            if(ptr(a[i]))
            {
                cout << a[i] << endl;
            }
        }
    }
    
    int main(void)
    {
    
       int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
       printfArray(a, sizeof(a) / sizeof(a[0]), div2);
       system("pause");
       return 0;
    }
    

    lambda表达式本质上是一个函数

    {};

    capture{body};

    capture:捕捉外界的变量。如果捕获任意值则不能作为指针使用。捕获外界所有值:[=] 值传递 [&] 引用传递
    argument:参数
    body:函数体

    使用形式:

    auto fn = [](int n)->bool{ return n % 2 == 0;};
    fn(10);
    //或者
    [](int n)->bool{ return n % 2 == 0;}(100);
    

    例如:

    #include <iostream>
    using namespace std;
    //利用lamdab表达式进行排序
    int A(int n)
    {
        return n;
    }
    void sort(int a[], size_t len, int (*ptr)(int n))
    {
        for(size_t i = 0;i < len - 1;++i)
        {
            for(size_t j = i +1;j < len; ++j)
            {
                if(ptr(a[i]) > ptr(a[j]))
                {
                    int t = a[i];
                    a[i] = a[j];
                    a[j] = t;
                }
            }
        }
    }
    
    int main(void)
    {
        int a[10] = {1, -2, 4, 7, 5, -6, 8, 9, 0, 3};
        auto fn = [](int n){return n*n;};
        sort(a, sizeof(a) / sizeof(a[0]), fn);
        for(auto &x : a)
        {
            cout << x << endl;
        }
        system("pause");
        return 0;
    }
    
    
    //利用lamdab快速排序
    #include<cstdlib>
    #include <iostream>
    using namespace std;
    int main(void)
    {
        int a[10] = {1,2,3,4,5,6,7,8,9,0};
        ::qsort(a,sizeof(a)/sizeof(a[0]),sizeof(a[0]),[](void const *p1, void const *p2)->int
        {
            int *q1 = reinterpret_cast <int *>(const_cast <void *>(p1));   //void *p = nullptr; 是万能指针
            int *q2 = reinterpret_cast <int *>(const_cast <void *>(p2));   //将宽范围的往窄范围赋予,需要进行强制类型转换
            return *q1 - *q2;
    
        });
        for(auto &x : a)
        {
            cout << x << endl;
        }
    }
    

    this指针

    记住用法:
    ···C++
    void (Demo::*pfn)() = nullptr;
    pfn = &Demo::fn; //fn为成员函数

  • 相关阅读:
    vue基础指令了解
    django中间件和auth模块
    form组件及cookie和session
    ajax学习相关
    数据库优化查询相关
    Django ORM必会13条之外的查询方法
    Django ORM单表查询必会13条
    Django学习之路05
    Django学习之路04
    Django学习之路03
  • 原文地址:https://www.cnblogs.com/wsl540/p/13732967.html
Copyright © 2011-2022 走看看