Hi,
I have a pointer to an array of structures in a DLL that I need to sort. I have searched the Internet but I can’t find an example that reflects what I am doing.
In a calling program I have a structure defined in the following manner and an array is created using the struct.
1 2 3 4 5 6
struct BinData
{
int Number;
double Amplitude;
int Correction;
}
I pass the array to a function in a DLL like below void Calculate(BinData *bins, constint binCount)
With as many as 3000000 rows what is the best and fastest way to sort this array by the Amplitude field?
Start with the std::sort function. You provide the function with the comparison. Here's an example showing how to call the sort function on the array, with some output so you can see it's sorted.
Note that the other form of sort that anup30 did use: std::sort( array.begin(), array.end() );
does call operator< that accepts array elements. The op< is the default comparator. If you always order BinData by amplitude, then the default is convenient.
anup30 did supply such operator< as member function, but could have written a standalone functions:
1 2 3 4 5 6 7 8 9
booloperator< ( BinData* a, BinData* b )
{
return a->amplitude < b->amplitude;
}
booloperator< ( const BinData& a, const BinData& b )
{
return a.amplitude < b.amplitude;
}
Repeater did use the sort that takes a comparator function (object) as argument. The function could be standalone and have name, but the C++11 lambda syntax allows definition of such function in-place.
If you need different sorts, then you need the argument version (but you can have a default too).