使用我的define函数错误进行c ++ STL排序

hrw*_*per 3 c++ stl

我知道我可以使用我的define函数对数组进行排序,就像这样:

bool cmp(int a, int b){
    return a > b;
}

class SortTest{
public :
    void testSort(){
        int a[] = { 1, 3, 4, 7, 0 };
        int n = 5;
        sort(a, a + n, cmp);                //work
        for (int i = 0; i < n; i++){
            cout << a[i] << " ";
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

但是如果我在SortTest类中使用函数cmp,它就不起作用了.

class SortTest{
public :
    bool cmp(int a, int b){
        return a > b;
    }
    void testSort(){
        int a[] = { 1, 3, 4, 7, 0 };
        int n = 5;
        sort(a, a + n, &SortTest::cmp);             // not work
        for (int i = 0; i < n; i++){
            cout << a[i] << " ";
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

我定义了两个模板SortClass和SortClass2就像更大的模板 ,SortClass2是使用operator()而SortClass是cmp,只使用operator()工作.

template <class T> struct SortClass {
    bool cmp (const T& x, const T& y) const { return x > y; }
};

template <class T> struct SortClass2 {
    bool operator()(const T& x, const T& y) const { return x > y; }
};

class SortTest{
public :
    bool operator() (const int& x, const int& y) const { return x > y; }
    void testSort(){
        int a[] = { 1, 3, 4, 7, 0 };
        int n = 5;
        //sort(a, a + n, &SortClass<int>::cmp); //not work
        //sort(a, a + n, SortClass2<int>());    //work
        sort(a, a + n, SortTest());             //work
        for (int i = 0; i < n; i++){
            cout << a[i] << " ";
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是为什么在SortTest类中的cmp函数不起作用,但是使用operator()是有效的吗?如果cmp函数不在类中,它工作正常.非常感谢.

use*_*027 5

问题是&SortClass<int>::cmp将指针传递给成员函数SortClass,但是sort没有任何实例来调用成员函数.

只需尝试添加这些代码段:

int i = 5, j = 10;
(&SortClass<int>::cmp)(i, j) // won't work

SortClass<int> test;
test.cmp(i,j) // will work because it is being called on an instance.
Run Code Online (Sandbox Code Playgroud)

如果将其更改为静态函数,则可以使其工作:

bool cmp (const T& x, const T& y) const { return x > y; }
Run Code Online (Sandbox Code Playgroud)

至:

static bool cmp (const T& x, const T& y) { return x > y; }
Run Code Online (Sandbox Code Playgroud)

请注意,const必须删除函数参数和函数体之间,因为静态函数不适用于此指针.


另一方面,为什么所有这些类?C++的优势之一是你可以混合使用编程范例,而不必像Java那样拥有类中的所有内容.为什么不将它们作为自由函数?