我希望在某个类中,按照特定的顺序对某个结构体的向量进行排序。我已经在类中编写了结构体的定义和谓词函数,并在该类的方法中使用这些结构体和函数运行了std::sort。但是编译错误发生了。gcc版本为4.0.1,操作系统为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;
}
错误信息过于庞大和复杂,以下是其前两行。
sortSample.cpp:在成员函数'int sample :: func()'中:
sortSample.cpp:51:错误:类型为'sample :: s,sample :: s'的参数与'type bool(sample :: *)(sample :: s,sample :: s)'不匹配
...
除了上述方法外,还可以通过以下方式正确运行代码。
- 在
class sample
之外定义struct s
和函数cmp()
。 - 删除函数
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 {
// ...
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;
}
};
有人能解释一下这种行为的机制吗?为什么第一种方法会导致编译错误?
谢谢。