以下是一个节省空间的方法:
struct Outer {
int i;
struct Inner {
int j;
uint16_t where;
Outer& outer() {
Inner* first = this - where;
char* addr = reinterpret_cast<char*>(first) - offsetof(Outer, items);
return *reinterpret_cast<Outer*>(addr);
}
};
Inner items[1000];
Outer() {
for (uint16_t ii = 0; ii < 1000; ++ii)
items[ii].where = ii;
}
};
如果您在一台64位计算机上使用32位整数,那么
sizeof(Inner)
从16到8字节(不打包)或12到6字节(打包)。
如果要节省更多空间,可以执行以下操作:
struct Outer {
int i;
struct Inner {
int j;
Outer& outer() {
Inner* sentinel = this;
while (sentinel.j != INT_MIN)
--sentinel;
char* addr = reinterpret_cast<char*>(sentinel) - offsetof(Outer, sentinel);
return *reinterpret_cast<Outer*>(addr);
}
};
Inner sentinel = {INT_MIN};
Inner items[1000];
};
但是然后
outer()
是o(n)而不是o(1),您必须确保
INT_MIN
(或某些哨兵值)从未用于
items
。