[英]Implicit conversion to comparison function object (functor) for std::sort but not std::map?
我一直在使用带有 function 的std::sort
作为比较 function。 function 被隐式转换为仿函数(通过 GCC)。 我在声明std::map
类型时尝试了相同的方法,但这失败了。
使用g++ g++ -Wall -Wextra -std=gnu++14 -pedantic
:
#include <map>
#include <algorithm>
#include <vector>
struct S { int i; };
struct Payload { bool b; };
bool compare(const S* const& lhs, const S* const& rhs)
{
return lhs->i < rhs->i;
}
using MyMap = std::map<const S*, Payload, compare>;
static void foo([[maybe_unused]] const MyMap&) {}
int main()
{
std::vector<const S*> vs;
std::sort(vs.begin(), vs.end(), compare); // OK
MyMap m;
foo(m);
}
这是 output:
main.cpp:13:50: error: type/value mismatch at argument 3 in template parameter list for 'template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map'
13 | using MyMap = std::map<const S*, Payload, compare>;
| ^
main.cpp:13:50: note: expected a type, got 'compare'
有没有一种方法可以将函子传递给map
声明,而无需手动定义函子 class (因为可以使用std::sort
)?
您似乎混淆了类型和值。 std::sort
的第三个参数是一个值, std::map
的第三个参数是一个类型。
using MyMap = std::map<const S*, Payload, bool (*)(const S* const&, const S* const&)>;
完全合法。
然后你可以写
MyMap my_map(compare);
PS在您的排序示例中没有隐式转换为仿函数。 作为模板 function 可以使用任何合法的 function 调用运算符调用排序。 这包括函子和 function 指针(除其他外)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.