关于成员函数作为STL算法参数
类的成员函数可以作为STL算法的参数,只是需要加mem_fun_ref配接器,但是我将成员函数作为sort()的参数,企图对类对象排序时却无法工作了。代码如下:
class Point
{
public:
int x; int y;
Point(int xx, int yy)
{
x = xx;
y = yy;
}
friend ostream& operator < <(ostream& out,const Point& p)
{
out < < p.x < < " " < < p.y < < endl;
return out;
}
bool LargeThan(const Point& p)
{
return (x > p.x)|| ((x==p.x) && (y > p.y));
}
void print()
{
cout < < x < < " " < < y;
}
void printWithPre(char* s)
{
cout < < s < < " " < < x;
}
};
int main()
{
vector <Point> vec;
// initialize vec
.......
for_each(vec.begin(), vec.end(),
bind2nd(mem_fun_ref(&Point::printWithPre), "hello: "));
// works fine
//sort(vec.begin(), vec.end(),
mem_fun_ref(&Point::LargeThan)); // doesn 't work
}
谁能说说其中的原因?谢谢。
[解决办法]
std::sort 要求 BinaryPredicate, 如果你要用memeber function的话,加上this指针,就有3个参数了。 mem_func是从binary_function继承下来的。
解决方案:自己扩充mem_func,或者使用boost::bind,它目前可到9(10?)个参数。