# Thread: How to Qsort an array of structs by one of its members?

1. ## How to Qsort an array of structs by one of its members?

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={1,4,4,3,5,6,4,4};
int data2={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 << 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;`
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) 2. Instead of using qsort, use std::sort. Your compare function could then become:
Code:
```bool compare(const item_database& a, const item_database& b)
{
return a.token < b.token;
}```
Or you could use a lambda instead, if possible.

Generally, unless you have some special reason, you should prefer std::sort to qsort. 3. I have the feeling that qsort is used in C. Here I have implemented it.

As a result, I would suggest you to use std::sort. I have implement this too, here. Of course, you have to modify a bit the code for your needs. (the compar function).

In order for you to understand how unusual is for someone to use qsort in cpp, when I saw the title of the thread I thought you had posted C code in the wrong thread. 4. Even your compare function for ints is wrong. It is returning -1 for items which are equal, when it must return zero in that case.
That will cause it to sort incorrectly in some cases.

Use use std::sort instead, as described. Popular pages Recent additions 