-
qsort Comparator
Hi, i would like to sort an array of object by their atribute, this is my testing project, the biggest problem is in compare function
Thanks for help
Code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include "string.h"
#include <cstdlib>
using namespace std;
using std::sort;
class A{
public:
int size;
public :
int get(){
return size;
}
};
int compare (const void *a, const void *b) {
A *aO = *(A **)a;
A *bO = *(A **)b;
return ( aO.get() - bO.get()); // now i gets error request for member of get in aO which is none-class A* dunno why
}
int main()
{
A **aray;
array= new A *[4];
for(int i=0; i < 4; i++)
{
array[i] = NULL;
}
A* a= new A();
A* b= new A();
A* c= new A();
A* d= new A();
a->size=15;
array[0]= b;
array[1]= a;
array[2]= c;
array[3]= d;
array[0]->size=12;
array[1]->size=10;
array[2]->size=20;
array[3]->size=15;
qsort (pole[0],4,sizeof(A*),compare);
for(int i=0; i < 3; i++)
{
if(array[i]!= NULL)
cout << array[i]->get() << endl;
}
return 0;
}
-
a0 and b0 are pointers. Use the -> syntax to access members via pointers, not the . operator.
Also, your obvious attempt at hacking around with defining a0 and b0 in the form "A *a0 = *(A **)a" is unnecessary (and, worse, means your code has undefined behaviour, since it dereferences a pointer to a type it isn't). "A *a0 = (A *)a" will suffice.
-
Out of curiosity, but you seem aware of std::sort, so is there any special reason why you want to use qsort? Just for experimentation?
-
If your goal is to sort things, then just use std::sort, not qsort.
You need only define a less-than operator:
Code:
bool operator < (const A *left, const A *right)
{
return left->get() < right->get();
}