C++ 在地图中使用 Lambda

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8736997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:03:04  来源:igfitidea点击:

Using Lambdas in Maps

c++c++11lambda

提问by ygr

I'm trying to implement a map with a lambda function in C++11 as such

我正在尝试在 C++11 中使用 lambda 函数实现映射

std::map<int, int, [](const int&a, const int& b) { return a < b; }> test;

but that fails with

但这失败了

error: type/value mismatch at argument 3 in template parameter list for ‘template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map'

error: expected a type, got ‘{}'

error: invalid type in declaration before ‘;'token

错误:模板参数列表中参数 3 的类型/值不匹配 ‘template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map'

错误:期望一个类型,得到 ‘{}'

错误:‘;'令牌前声明中的无效类型

Any advice?

有什么建议吗?

回答by Benjamin Lindley

You need to pass the type of the lambda as a template argument, not the lambda itself. What you want is this:

您需要将 lambda 的类型作为模板参数传递,而不是 lambda 本身。你想要的是这个:

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:

尽管实际上,由于您的 lambda 没有捕获,它实际上可以存储在函数指针中,因此,您也可以这样做:

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:

虽然我发现第一个更具可读性。虽然使用函数指针类型更加通用。即它可以接受与该签名匹配的任何函数指针或非捕获 lambda。但是,如果您将 lambda 更改为要捕获,它将不起作用。对于更通用的版本,您可以使用std::function,即:

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.

只要签名匹配,这将适用于任何函数,lambda(捕获与否)或函数对象。