【发布时间】:2009-10-22 06:42:03
【问题描述】:
我想在特定类中以特定顺序对特定结构的向量进行排序。我已经在一个类中编写了结构和谓词函数的定义,并在具有这些结构和函数的类的方法中运行 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: 错误: 'bool (sample::)(sample::s, sample::s)' 类型的参数不匹配'bool (sample::*)(sample::s, sample:: s)'
...
代替上述方法,代码可以通过以下方式正确运行。
- 定义
struct s和函数cmp()在class sample之外。 - 删除
函数
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;
}
};
谁能说出这种行为的机制?为什么第一种方法会调用编译错误?
谢谢。
【问题讨论】:
标签: c++