Sorting a buffer using STL SORT

2019-08-17 10:33发布

问题:

I am trying to sort a buffer using STL sort. Now, Im using qsort but i read that stlsort has a better performance because of the inline "compare" function. The buffer has elements of size 52. It has, for example, 1024 elements of size 52. Here is a part of my code. It is working well, but I want to use the STL sort. I am sorting a fixed length file. Each fixed length file has a record size, so the user has to inform the record size. In the example below i put 52.

HANDLE hInFile;
char * sharedBuffer;
int recordSize = 52;
sharedBuffer = new char [totalMemory];
hInFile = CreateFile(LPCSTR(filePathIn), GENERIC_READ, 0, NULL, OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN, NULL); 
ReadFile(hInFile, sharedBuffer, totalMemory, &dwBytesRead, NULL);
CloseHandle(hInFile);

qsort(sharedBuffer, dwBytesRead/recordSize, recordSize, compare); //sort using qsort but i want to use the slt sort

WriteFile(hOutFile, sharedBuffer, dwBytesRead, &dwBytesRead, NULL);
CloseHandle(hOutFile); //write the sorted buffer to disk

int compare (const void * a, const void * b)
{
return memcmp((char *)a, (char *)b, recordSize);
}

Can i read the file in other way? Using a vector, iterators?

Thanks for the help!

回答1:

Sure you can. You define a type called (say) MyRecordType, which describes the records that you sorting. Then you define a routine that sorts two MyRecordTypes, and you call std::sort passing the array and the comparison function.

Example code (untested):

typedef struct {
    char foo[52];
} MyRecordType;

bool comp ( const MyRecordType &lhs, const MyRecordType &rhs ) {
    return lhs.foo[0] < rhs.foo[0]; // some ordering criteria
}

// figure out how many records you are going to process
MyRecordType * sharedBuffer = new MyRecordType [ count ];
// read into sharedBuffer as before (though one at a time would be better, due to packing concerns)
std::sort ( sharedBuffer, sharedBuffer + count, comp );
// write back out