2012-07-14 94 views
0

我想排序使用STL排序的緩衝區。現在,我使用qsort,但我讀了stlsort有更好的表現,因爲內嵌「比較」功能。緩衝區的大小爲52的元素。例如,它有1024個大小爲52的元素。這是我的代碼的一部分。它運行良好,但我想使用STL排序。我正在排序一個固定長度的文件。每個固定長度的文件都有記錄大小,所以用戶必須通知記錄大小。在下面的例子中,我把52.使用STL排序緩衝區排序

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); 
} 

我可以以其他方式讀取文件嗎?使用矢量,迭代器?

感謝您的幫助!

回答

0

當然可以。 您定義了一個稱爲(說)MyRecordType的類型,它描述了您排序的記錄。 然後你定義一個排序兩個MyRecordTypes的例程,然後你調用std :: sort傳遞數組和比較函數。

實施例的代碼(未測試):

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 
+0

也可以使用的載體而不是一個簡單的陣列。這會讓閱讀記錄更復雜一點,儘管並不多。 – 2012-07-14 23:28:34

+0

在這個例子中,我將記錄的大小定義爲52.但是我需要動態分配它。如果我將「char foo [52]」更改爲「char * foo」並動態分配,它是否會起作用?可能不會。 – 2012-07-15 22:47:05

+0

可能不是;沒有。爲了幫助你,我需要更多的信息。 – 2012-07-16 00:13:22