0

Hello everyone, I'm trying to implement qsort on a struct with the double as a pivot:

typedef struct{
    char sequence[9];
    int occurance;
    double prob;
    }tuple;

    ......


    int compare (const void *x, const void *y){
    if (x < y) return -1;
    if (x > y) return 1;
    else return 0;

}

...
qsort(x,k,sizeof(tuple),compare);

Now I was trying to access members only to find that it doesn't work.

int compare (const void *x, const void *y){
    if (x.prob < y.prob) return -1;
    if (x.prob > y.prob) return 1;
    else return 0;



}

error: request for member ‘prob’ in something not a structure or union

I was thinking that maybe I have to do something extra, like create a special case of the quicksort algorithm. What would you suggest?

3
Contributors
2
Replies
11
Views
4 Years
Discussion Span
Last Post by deceptikon
0

Something like this should work:

#include <iostream>

using namespace std;
void Pause()
{
    cin.ignore();
    cin.get();
}
struct test
{
    char sequence[9];
    int occurance;
    double prob;
};
int compare (const void * x, const void * y)
{
    const test * dx = (const test *) x;
    const test * dy = (const test *) y;
    if (dx->prob < dy->prob) return -1;
    if (dx->prob > dy->prob) return 1;
    else return 0;
}
int main()
{
    test testarray[3];
    testarray[0].prob = 10;
    testarray[1].prob = 5;
    testarray[2].prob = 7;
    for(int i=0;i<3;i++)
        cout << testarray[i].prob << ",";
    cout << endl;
    qsort(testarray,3,sizeof(test),compare);
    for(int i=0;i<3;i++)
        cout << testarray[i].prob << ",";
    cout << endl;
    Pause();
    return 0;
}
0

I was thinking that maybe I have to do something extra, like create a special case of the quicksort algorithm. What would you suggest?

The problem is that the comparison callback accepts pointers to void, which then need to be cast into the correct type before you can do any comparisons or member selection. tinstaafl's example does this, but he didn't mention what he did to fix the error and why. It's also in C++, but that can be forgiven as the C++isms are extraneous to the solution for your problem. ;)

int compare (const void * x, const void * y)
{
    const test * dx = (const test *) x;
    const test * dy = (const test *) y;
    if (dx->prob < dy->prob) return -1;
    if (dx->prob > dy->prob) return 1;
    else return 0;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.