Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sorting a arrary of structures (qsort)

Status
Not open for further replies.

Premalm

Programmer
Mar 20, 2002
164
US
Hey guys,

Can qsort in vc++ be used to sort an array of structures.

Thanks
Premal
 
I have a struct
struct CFGStruct
{
CString RecPtr;
CString ParcelString;
CString AmountString;
} ParcelArray[50000];

How do I define qsort for this structure ? My key is ParcelString.

Thanks
Premal
 
int compare(const void *elem1, const void *elem2 ) )
{
if( ((CFGStruct*)elem1)->ParcelString > ((CFGStruct*)elem2)->ParcelString ){
return 1;
}
else if( ((CFGStruct*)elem1)->ParcelString > ((CFGStruct*) elem2)->ParcelString ){
return -1;
}
else{
return 0;
}
}

....
qsort(ParcelArray,50000,sizeof(*ParcelArray), compare);

p.s. 50000 bad idea
use int const nArraySize = 50000;

best regards,
alex,
 
...or, since we're talking about CString, simply:

int compare(const void *elem1, const void *elem2 ) )
{
CFGStruct* struct1 = (CFGStruct*)elem1;
CFGStruct* struct2 = (CFGStruct*)elem2;

return struct1->ParcelString.Compare(struct2->ParcelString);
}
.
.
.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top