【发布时间】:2014-08-29 09:52:35
【问题描述】:
假设我在 C++ 中有一些 POD struct Foo,我想将其放入像 set<Foo> 这样的有序容器中。我不关心使用哪种排序,只关心它是一致的和快速的。最好的方法是什么?
更具体地说,假设我在一台带有sizeof(long)==8 的 64 位机器上。说类是:
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
}
padding 字段只是为了确保大小是 8 的倍数。
注意sizeof(Foo) 是 48,所以它的内容可以用 6 个unsigned longs 表示,这显然是进行比较的最佳方式,而不是遍历每个字段。
编译器可以自动为我执行此操作吗?或者我是否必须使用字段unsigned long data[8] 定义union,或者在Foo 的operator< 方法中将Foo * 转换为unsigned long *?
请注意,如果没有填充字段,则必须生成 5 个 unsigned long 比较,然后是 long、short 和 char 比较。这整件事有点乱。
这个问题必须一直出现,所以我猜有一些最好/最好的方法来处理它。
【问题讨论】:
-
你固定在
std::set上吗?也许std::unordered_set结合散列函数可能是一个不错的选择(如果您只使用它进行快速查找,并且不需要顺序)。
标签: c++ stl containers comparison-operators