繁体   English   中英

将 C++ lambda 作为参数传递给非模板化 function

[英]Passing C++ lambda as argument to non templated function

正如我在谷歌上搜索std::function 工作比简单的 lambda function 慢

考虑以下用例,在使用 stl 排序算法时会出现std::function惩罚( v向量可能足够大并占用大约 N*GB 的数据):

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

using namespace std;

void sorter(std::vector<int>& v, std::function<bool(int a, int b)> f){
    std::sort(v.begin(), v.end(), f);
}

int main()
{
    std::vector<int> v = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
    for (auto val : v)
        cout << val << " ";
    cout << endl;

    int c = 4;
    auto f = [&c](int a, int b){ return a+b < c; };
    
    sorter(v, f);

    for (auto val : v)
        cout << val << " ";
    cout << endl;

    return 0;
}

如您所见,我创建了 lambda function f并将其传递给sorter function。 我的任务是保持sorter function非模板化,这就是为什么我试图将 lamda function 作为std::function 还是有更好的方法来做到这一点?

不捕获任何内容的 Lambda 可以使用+运算符转换为 function 指针:

void sorter(std::vector<int>& v, bool (*cmp)(int,int));

int main() {
  auto const cmp = +[](int a, int b) { return a < b; };
  vector<int> v{3, 2, 1};
  sorter(v, cmp);
}

但如果它确实捕获了某些东西,您应该将其设为模板,或使用std::function 没办法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM