C++ std :: sort with Class中的谓词函数

kos*_*sei 4 c++

我想在某个类中按某种顺序对某个结构的向量进行排序.我在类中编写了struct和predicate函数的定义,并在具有这些struct和function的类的方法中运行std :: sort.但是发生了编译错误.gcc版本是4.0.1,OS是Mac OSX.代码如下:

class sample {
public:
  struct s {
    int x;
    int y;
  };

  bool cmp (struct s a, struct s b) {
    if (a.x == b.x)
      return a.y < b.y;
    else
      return a.x < b.x;
  }

  int func(void) {
    std::vector <struct s> vec;

    // ...

    sort(vec.begin(), vec.end(), cmp);  // compilation error

    // ...

    return 0;
  }
};

int main(void) {
  sample *smp = new sample();
  smp->func();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误消息庞大而复杂.所以这是前两行.

sortSample.cpp:在成员函数'INT ::样品FUNC()':
sortSample.cpp:51:错误:类型的参数'布尔(样品::)(样品:: S,样品:: S)'不匹配'bool(sample ::*)(sample :: s,sample :: s)'
...

代替上述方法,代码可以通过以下方式正确运行.

  1. 在外面定义struct s和运作.cmp()class sample
  2. 删除功能cmp(),并定义的操作符重载<struct s.

每种方法的示例代码如下.

1)

struct s {
  int x;
  int y;
};

bool cmp (struct s a, struct s b) {
  if (a.x == b.x)
    return a.y < b.y;
  else
    return a.x < b.x;
}

class sample {
// ...
Run Code Online (Sandbox Code Playgroud)

2)

struct s {
  int x;
  int y;

  bool operator<(const struct s & a) const {
    if (x == a.x)
      return y < a.y;
    else
      return x < a.x;
  }
};
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉这种行为的机制吗?为什么第一种方法会调用编译错误?

谢谢.

Nav*_*een 12

在第一种情况下cmp 声明为其成员函数,class sample因此需要this用于调用它的指针.由于this指针不可用,编译器正在抱怨它.您可以通过声明cmpstatic函数来使其工作,因为静态函数不需要此指针进行调用.在第二种情况下,由于cmp再次被声明为独立函数,因此它的行为与静态函数相同.在第三种情况下(带有重载运算符),排序算法将负责为向量中的每个对象调用函数,从而进行编译.


use*_*783 6

由于cmp与任何特定的样本实例无关,因此将其作为静态成员函数.


aJ.*_*aJ. 5

可以在您的可能性中列出的第三种方法是使用operator():

bool operator() (const s& a, const s& b) const
{
    if (a.x == b.x)
        return a.y < b.y;
    else
        return a.x < b.x;
}

sort(vec.begin(), vec.end(), *this);
Run Code Online (Sandbox Code Playgroud)