简体   繁体   English

C ++中POD类的快速默认排序

[英]Fast default ordering for POD class in C++

Say I have some POD struct Foo in C++ which I want to put into an ordered container like set<Foo> . 假设我在C ++中有一些POD struct Foo ,我想将其放入有序容器中,例如set<Foo> I do not care about which ordering is used, only that it be consistent and fast. 我不在乎使用哪种排序,只是在乎它是否一致且快速。 What is the best way to do this? 做这个的最好方式是什么?

More concretely, say I am on a 64-bit machine with sizeof(long)==8 . 更具体地讲,假设我使用的是sizeof(long)==8的64位计算机。 Say the class is: 说课是:

 struct Foo{
  long key; //8 bytes : 8 total
  int fum;  // 4 bytes : 12 total
  short n;  // 2 bytes : 14 total
  short n[3];  //6 bytes : 20 total
  char bar[5];  // 5 bytes : 25 total
  char name[23]; //22 bytes : 47 total
  char padding[1]; // 1 byte : 48 total 
 }

the padding field is just to make sure the size is multiple of 8. padding字段只是为了确保大小是8的倍数。

Note that sizeof(Foo) is 48 so its contents can be represented in 6 unsigned long s, which is obviously the best way to do comparisons, rather than walking through each field. 请注意, sizeof(Foo)为48,因此其内容可以用6个unsigned long s表示,这显然是进行比较的最佳方法,而不是遍历每个字段。

Can the compiler do this for me automatically? 编译器可以自动为我执行此操作吗? Or do I have to either define a union with a field unsigned long data[8] , or cast a Foo * to unsigned long * in my operator< method for Foo ? 还是我必须要么定义一个union有场unsigned long data[8]或投下Foo *unsigned long *在我的operator<Foo

Note that if there is no padding field, then one must generate 5 unsigned long comparisons, followed by comparisons of a long , a short , and a char comparison. 请注意,如果没有填充字段,则必须生成5个unsigned long比较,然后是longshortchar比较的比较。 This whole thing is kind of messy. 这整个事情有点混乱。

This issue must come up all the time, so I am guessing there is some best/best way to handle it. 这个问题必须一直出现,所以我猜想有一些最好的/最好的方法来处理它。

If you want to compare using the struct actual value, it's best to define an operator< that has a bit more logic and gives some kind of logical ordering between the fields. 如果要使用struct实际值进行比较,则最好定义一个operator< ,它具有更多的逻辑并在字段之间给出某种逻辑顺序。

If you just want the objects sortable for fast access, you can just hold the pointes. 如果只希望对对象进行排序以进行快速访问,则只需按住指针即可。 Those are just numbers, and are sortable. 这些只是数字,并且可以排序。

If you want to use the actual struct data, but don't care about any kind of ordering between the members, you can just use memcmp with sizeof(Foo) . 如果您想使用实际的struct数据,但不关心成员之间的任何排序,则可以将memcmpsizeof(Foo)

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

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