I am versed in qsorting struct members within a struct instance, as in the example below:
Code:
#include <iostream>
#include <stdlib.h>
using namespace std;
struct item_database {
int data1[8]={1,4,4,3,5,6,4,4};
int data2[8]={1,7,6,3,4,2,11,11};
}a;
int compare (const void* element1, const void* element2)
{
if(*(int*)element1 >= *(int*)element2)
return -1;
else
return 1;
}
int main()
{
item_database a;
item_database* aptr = &a;
qsort(aptr->data1,8, sizeof(int), compare);
cout << a.data1[1] << endl;
return 0;
}
What I CANT do however is to sort an array of structs by one of its members. This is a complete different problem even if it sounds similar.
In other words, the problem is this; Say we have a struct:
Code:
struct item_database {
int key;
string token;
};
Then we declare an array of this struct in the heap:
Code:
item_database *idptr = new item_database[700000];
and initialize its values.
How would one go about sorting this heap array of structs by its member function "token"?
I used the following call to qsort (standard library) and call to the compare function but it doesnt work:
Code:
qsort (idptr, 1000, sizeof(string), compare);
Code:
int compare (const void* a, const void* b)
{
if (*(char*)a >= *(char*)b)
return 1;
else
return -1;
}
Or in more lamens terms say we have the following stuct instances:
Key: Token:
1 Hello
2 World
3 How
4 Are
5 You
Then I need those structs to order according to token (alphabetically, increasing or decreasing depending whats in our compare function)