首页 > 解决方案 > 隐式转换为 std::sort 但不是 std::map 的比较函数对象(函子)?

问题描述

我一直在使用std::sort函数作为比较函数。该函数被隐式转换为函子(通过 GCC)。我在声明std::map类型时尝试了同样的方法,但是失败了。

编译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);
}

这是输出:

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声明,而无需手动定义仿函数类(因为可以使用std::sort)?

标签: c++

解决方案


您似乎混淆了类型和值。to的第三个参数std::sort是一个值,to的第三个参数std::map是一个类型。

using MyMap = std::map<const S*, Payload, bool (*)(const S* const&, const S* const&)>;

完全合法。

然后你可以写

MyMap my_map(compare);

PS在您的排序示例中没有隐式转换为仿函数。作为模板函数,可以使用函数调用运算符合法的任何内容调用 sort。这包括函子和函数指针(除其他外)。


推荐阅读