简体   繁体   English

内存映射文件中对象的排序

[英]sorting of objects in memory mapped file

I have a structure as below: 我的结构如下:

struct XX
{
   int x;
   char szT[200];
   int y;
} ;

I have a file that stores several of these XX objects, written through fwrite call. 我有几个存储这些的文件XX对象,通过书面fwrite调用。 Now when I read the file as a memory mmaped file using mmap, I use as: 现在,当我使用mmap将文件读取为内存mmaped文件时,将用作:

// sz = size of the file in bytes
// fd = file descriptor of the file opened through fopen in O_RDWR mode
char *p = (char *) mmap(0,sz,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
unsigned int N = (sz / sizeof(XX)); // number of objects

Thus, if I have N objects of type XX , I may access the first object as: 因此,如果我有N个类型为XX对象,则可以按以下方式访问第一个对象:

XX *px = (XX*) p;

And, i-th object I can access as px + i where i <= N . 而且,第i-th对象我可以作为px + i访问,其中i <= N May I use std::sort to sort the contents of a memory mapped file being accessed as px being the pointer of first record, and px+i pointing to i-th record. 我可以使用std::sort对正在访问的内存映射文件的内容进行排序,因为px是第一条记录的指针,而px+i指向i-th记录。 I don't like to store px, px+1, px+2 etc in a vector of XX pointers as vector<XX*> , as I can access the records directly from the memory-mapped file. 我不喜欢将px, px+1, px+2等存储在XX指针的向量中,作为vector<XX*> ,因为我可以直接从内存映射文件访问记录。 Please suggest. 请提出建议。

Read documentation of std::sort 阅读std::sort文档

The following compiles cleanly. 以下内容可以干净地编译。 It sorts a raw array with a peculiar lambda (comparing squares of numbers) 它使用特殊的lambda(比较数字的平方)对原始数组进行排序

 #include <algorithm>
 #include <functional>

 void sort_array(int *p, size_t n) {
   std::sort(p, p+n, [=](int x, int y) { return x*x < y*y; });
 }    

You should be able to adapt that to your situation: 您应该能够使它适应您的情况:

 void sort_xx (XX*p, size_t n) {
   std::sort(p, p+n, [=](const XX& x, const XX& y) 
    { return strcmp(x.szT, y.szT)<0; });
 }

Read more about lambda expressions in C++ . 阅读有关C ++中的lambda表达式的更多信息。 [=] is a capture-list by value (actually by copy) notation (for all closed variables, theoretically the only one here being strcmp which the compiler is likely to optimize - so won't close it naively; probably the lambda-abstraction and its application would be inlined by an optimizing compiler). [=]是按值表示的捕获列表(实际上是按拷贝表示)(对于所有封闭变量,理论上唯一的一个是编译器可能会优化的strcmp ,因此不会天真地将其关闭;可能是lambda抽象并且其应用将由优化的编译器内联)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM