zoukankan      html  css  js  c++  java
  • C++ Lambda表达式和仿函数笔记

    C++11中引入了Lambda表达式,其语法如下:

    [capture list](parameter list)->return type { function body }

    参考博文:C++ 11 Lambda表达式

    示例:

    #include <iostream>
    int compare(const void *a, const void *b);
    int main()
    {
        using namespace std;
        int ints[] = { 9, 8, 6, 1, 0, -10, 100 };
        qsort(ints, sizeof ints / sizeof(int), sizeof(int), compare);
        for (int i : ints)
        {
            cout << i << ' ';
        }
        cout << endl;
        int arr[] = { 0, 1, -100, -1000, 0, 10 };
        qsort(arr, sizeof arr / sizeof(int), sizeof(int), [](const void *a, const void *b)->int
        {
            int arg1 = *static_cast<const int *>(a);
            int arg2 = *static_cast<const int *>(b);
            if (arg1 < arg2)
            {
                return -1;
            }
            if (arg1 > arg2)
            {
                return 1;
            }
            return 0;
        });
        for (int i : arr)
        {
            cout << i << ' ';
        }
        cout << endl;
        system("pause");
        return 0;
    }
    int compare(const void *a, const void *b)
    {
        int arg1 = *static_cast<const int *>(a);
        int arg2 = *static_cast<const int *>(b);
        if (arg1 < arg2)
        {
            return -1;
        }
        if (arg1 > arg2)
        {
            return 1;
        }
        return 0;
    }

    仿函数(functor),就是使一个类的使用看上去像一个函数。

    参考链接:仿函数_百度百科

    示例:

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    class FloatPrinter
    {
    public:
        void operator()(float f)
        {
            cout << f << ' ';
        }
    };
    int main()
    {
        vector<float> floats = { 3.14, 0, 6.28, 12.56 };
        for_each(floats.begin(), floats.end(), FloatPrinter());
        cout << endl;
        system("pause");
        return 0;
    }
  • 相关阅读:
    父类与子类之间的调用顺序
    ROW_NUMBER() OVER函数的基本用法用法
    String类
    代码块
    权限修饰符
    内部类
    final&static
    面向对象思想
    oracle存储过程常用技巧
    ORACLE EXECUTE IMMEDIATE 用法
  • 原文地址:https://www.cnblogs.com/buyishi/p/10364932.html
Copyright © 2011-2022 走看看