开发者

How to write comparator function for qsort?

class for example:

开发者_如何转开发
class classname{
public:
int N,M;
}; 

classname a > classname b if a.N>B.N


class classname{
  public:
    int N,M;

    bool operator< (const classname& other) const { return N < other.N; }
};

...
std::vector<classname> arr;
...
std::sort(arr.begin(), arr.end());

Or do you want to use C's qsort?

static int compare_classname (const void* a, const void* b) {
   const classname* _a = reinterpret_cast<const classname*>(a);
   const classname* _b = reinterpret_cast<const classname*>(b);
   return _a->N < _b->N ? -1 : _a->N > _b->N ? 1 : 0;
}
...
classname* arr = new classname[n];
...
qsort(arr, n, sizeof(arr[0]), compare_classname);


Since you're using C++, my advice would be to use std::sort instead of qsort. In this case, you normally implement your comparison function as operator<:

class classname { 
public:
    int N, M;

    bool operator<(classname const &other) const { 
        return N < other.N;
    }
};

Edit: If you insist on using C's qsort, the comparison function looks something like this:

int comparator(void *a, void *b) { 
     return ((classname *)b)->N - ((classname *)a)->N;
}


struct Functor {
   bool operator()(const classname & left, const classname & right) {
       return left.N < right.N;
   }
}

std::sort(container.begin(), container.end(), Functor());


If you specifically want to use qsort, then the function would be

int compare_classname(const void *a, const void *b)
{
    return static_cast<const classname*>(a)->N 
         - static_cast<const classname*>(b)->N;
}

But as others have said, you're better off with std::sort. It's typesafe, and probably faster since it can inline the comparisons.


This should work.

#include <stdlib.h>


class classname{
public:
    int N,M;
};

static int
cmp_classname(const void * p1, const void * p2) 
{
    const classname * pc1 = reinterpret_cast<const classname *>(p1);
    const classname * pc2 = reinterpret_cast<const classname *>(p2);
    if (pc1->N < pc2->N) {
        return -1;
    } else if (pc1->N > pc2->N) {
        return 1;
    }
    return 0;
}

And, yes, std::sort() is probably better.


In case you really want to you C's qsort (which you shouldn't if you use C++):

int compare(const void * a, const void * b)
{
  return static_cast<classname*>(a)->N < static_cast<classname*>(b)->N;
}

Then just pass compare as the 4th argument of qsort

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜