问题描述
我试图在C ++ 11中实现一个带lambda函数的映射,如
std :: map< ; int,int,[](const int& a,const int& b){return a< b; }>测试;
但是失败了
任何建议?
lambda作为模板参数,而不是lambda本身。你想要的是这个:
auto mycomp = [](const int& a,const int& b){return a< ; b; };
std :: map< int,int,decltype(mycomp)> test(mycomp);
虽然实际上,由于你的lambda没有捕获,它实际上可以存储在一个函数指针,所以你可以这样做:
std :: map< int,int,bool const int&)>
test([](const int& a,const int& b){return a< b;});
虽然我发现第一个更容易阅读。虽然使用函数指针类型是更通用的。即它可以接受与该签名匹配的任何函数指针或非捕获lambda。但是如果你改变你的lambda是捕获,它不会工作。对于更通用的版本,您可以使用 std :: function
,即:
std :: map< int,int,std :: function< bool(const int& const int&)>
这将适用于任何函数,lambda(捕获或不捕获)或函数对象,签名匹配。
I'm trying to implement a map with a lambda function in C++11 as such
std::map<int, int, [](const int&a, const int& b) { return a < b; }> test;
but that fails with
Any advice?
You need to pass the type of the lambda as a template argument, not the lambda itself. What you want is this:
auto mycomp = [](const int&a, const int& b) { return a < b; };
std::map<int, int, decltype(mycomp)> test(mycomp);
Although in fact, since your lambda has no captures, it can actually be stored in a function pointer, so alternatively, you could do this:
std::map<int, int, bool(*)(const int&,const int&)>
test([](const int&a, const int& b) { return a < b; });
Though I find the first much more readable. Although using the function pointer type is more versatile. i.e. It can accept any function pointer or non-capturing lambda that matches that signature. But if you change your lambda to be capturing, it will not work. For a more versatile version, you could use std::function
, i.e:
std::map<int, int, std::function<bool(const int&, const int&)>>
That will work with any function, lambda(capturing or not) or function object, as long as the signature matches.
这篇关于在地图中使用Lambdas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!