2012-07-14 92 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