Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

qsort comparison compilation error

Tags:

c++

My medianfilter.cpp class invokes qsort as seen below.

vector<float> medianfilter::computeMedian(vector<float> v) {
    float arr[100];
    std::copy(v.begin(), v.end(), arr);

    unsigned int i;
    qsort(arr, v.size(), sizeof(float), compare);
    for (i = 0; i < v.size(); i++) {
        printf("%f ", arr[i]);
    }
    printf("median=%d ", arr[v.size() / 2]);
    return v;
}

The implementaiton of my comparison is:

int medianfilter::compare(const void * a, const void * b) {
    float fa = *(const float*) a;
    float fb = *(const float*) b;
    return (fa > fb) - (fa < fb);
}

while the declaration in mediafilter.hpp is set private and looks like that:

int compare (const void*, const void*);

A compilation error occurs: cannot convert ‘mediafilter::compare’ from type ‘int (mediafilter::)(const void*, const void*)’ to type ‘__compar_fn_t {aka int (*)(const void*, const void*)}’

I don't understand this error completly. How do I correctly declare and implement this comparison method? Thanks!

like image 859
feder Avatar asked Feb 10 '26 14:02

feder


1 Answers

Compare is a non-static member function whereas qsort expects a non-member function (or a static member function). As your compare function doesn't seem to use any non-static members of the class, you could just declare it static. In fact I'm not sure what your median filter class does at all. Perhaps you just need a namespace.

Why not sort the vector directly instead of copying it into a second array? Furthermore your code will break if the vector has more than 100 elements.

The default behavior of sort does just want you need, but for completeness I show how to use a compare function.

I also changed the return type of your function because I don't understand why a function called computeMedian wouldn't return the median..

namespace medianfilter
{
    bool compare(float fa, float fb)
    {
        return fa < fb;
    }

    float computeMedian(vector<float> v)
    {
        std::sort(v.begin(), v.end(), compare);
        // or simply: std::sort(v.begin(), v.end());
        for (size_t i = 0; i < v.size(); i++) {
            printf("%f ", v[i]);
        }

        if (v.empty())
        {
            // what do you want to happen here?
        }
        else
        {
            float median = v[v.size() / 2]; // what should happen if size is odd?
            printf("median=%f ", median); // it was %d before
            return median;
        }
    }
}
like image 71
Neil Kirk Avatar answered Feb 13 '26 04:02

Neil Kirk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!