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;
}

 

相关文章:

  • 2022-12-23
  • 2021-07-17
  • 2021-12-07
  • 2021-05-29
  • 2021-08-19
  • 2021-04-29
猜你喜欢
  • 2021-10-01
  • 2021-11-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-16
相关资源
相似解决方案