【问题标题】:Member function as a map comparator?成员函数作为地图比较器?
【发布时间】:2013-11-10 03:06:31
【问题描述】:

我知道如何创建一个用作自定义地图比较器的函数:

std::map<std::string, std::string, bool (*)(std::string, std::string)> myMap(MapComparator);

bool MapComparator(std::string left, std::string right)
{
    return left < right;
}

但我不知道如何对 member 函数做同样的事情:

bool MyClass::MapComparator(std::string left, std::string right)
{
    return left < right;
}

【问题讨论】:

  • 必须是非静态成员函数吗?鉴于您的示例,您可以只声明成员函数static,因为它不访问任何非静态数据成员。
  • 创建仿函数或使用直接 lambda 可能会很好。 myMap(MapComparator)到底应该做什么?
  • @jogojapan 当然,它没有! 不过还没想到。谢谢。不过,如果可能的话,我想看看使用非静态成员函数的语法。 @WhozCraig 出于某些原因,我更喜欢成员函数而不是仿函数。而且我使用的是 VS2010,我不确定它是否支持 lambdas。 myMap(MapComparator) 在我班级的初始化列表中,我修复了示例代码。
  • @NPS 你不应该喜欢它。除其他事项外,成员需要一个 this 指针,该指针不能在 编译 时提供(映射比较器不像 std::sort 的比较器那样使用)。其次,即使您使用静态或全局函数,函数 pointers 也会使 糟糕 比较器。它们不值得内联,而适当地公开函数运算符的 type(例如 lambda 或 functor)做得非常好(通常,无论如何)。

标签: c++ comparator stdmap member-function-pointers


【解决方案1】:

您有多种选择:

在 C++11 中,您可以使用 lambda:

std::map<std::string, std::string, bool (*)(std::string, std::string)> myMap(
    [](string lhs, int rhs){ // You may need to put [this] instead of [] to capture the enclosing "this" pointer.
       return MapComparator(lhs, rhs); // Or do the comparison inline
    });

如果函数是静态的,使用::语法:

class MyClass {
public:
    static bool MyClass::MapComparator(std::string left, std::string right);
};
...
std::map<std::string, std::string, bool (*)(std::string, std::string)> myMap(MyClass::MapComparator);

如果函数是非静态的,则制作一个静态包装器,无论是成员还是非成员,并从中调用成员函数。

【讨论】:

  • +1 一般答案,尤其是[this] 捕获。
  • [this] 有效吗?我不知道您可以将捕获 lambda 函数转换为函数指针。
  • @Jacob 是的,这是允许的(见this Q&A)。
猜你喜欢
  • 2023-01-19
  • 2015-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
  • 2014-06-29
  • 2020-03-10
相关资源
最近更新 更多