使用STL SORT对缓冲区排序 [英] Sorting a buffer using STL SORT

查看:110
本文介绍了使用STL SORT对缓冲区排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用STL排序对缓冲区进行排序.现在,我使用qsort,但我读到stlsort具有更好的性能,因为它具有内联的比较"功能.缓冲区的元素大小为52.例如,缓冲区大小为1024,元素大小为52.这是我的代码的一部分.它运行良好,但我想使用STL排序.我正在排序固定长度的文件.每个固定长度的文件都有一个记录大小,因此用户必须告知记录大小.在下面的示例中,我输入了52.

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?

感谢您的帮助!

推荐答案

可以. 您定义一个称为(例如)MyRecordType的类型,该类型描述您排序的记录. 然后,定义一个对两个MyRecordTypes进行排序的例程,并调用std :: sort传递数组和比较函数.

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

这篇关于使用STL SORT对缓冲区排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆