I know I can use my define function to sort an array, just like this:
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] << " ";
}
}
};
But if I let function cmp in the SortTest class , it is not working.
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] << " ";
}
}
};
I define two template SortClass and SortClass2 like greater template , SortClass2 is use operator() and SortClass is cmp, only use operator() is working.
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] << " ";
}
}
};
so,my question is why cmp function in the SortTest class is not working ,but use operator() is working? And if the cmp function is not in the class,it is working fine. Thanks a lot.
The problem is that &SortClass<int>::cmp is passing a pointer to a member function of SortClass, but sort doesn't have any instance to call the member function on though.
Just try adding in these snippets:
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.
You can make it work if you change it to a static function, from:
bool cmp (const T& x, const T& y) const { return x > y; }
to:
static bool cmp (const T& x, const T& y) { return x > y; }
note that the const between the function arguments and function body has to be removed, since a static function doesn't work on a this pointer.
On another note, why all these classes? One of the strengths of C++ is that you can mix programming paradigms and you don't have to have everything in a class like in Java. Why not have them as free functions?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With