如何创建结构的结构结构,等等嵌套多个结构?

How do i create struccture of a structure of a structure, ect. nesting multiple structures?

本文关键字:结构 嵌套 创建 何创建      更新时间:2023-10-16

我在弄清楚如何实现多个结构的嵌套时遇到了问题,目标是拥有仓库,其中有仓库,其中有带货架的货架,货架有放置物品及其 2 位 ID 的地方。现在我的代码看起来像这样:

#include<iostream>
struct place{
unsigned short place_[65545][2];
};
struct shelf{
place shelf_[128];
};
struct rack{
shelf rack_[128];
};
struct warehouse{
rack warehouse_[128];
shelf handy_warehouse_shelf_;
};
struct depot{
warehouse depot_[128];
rack handy_rack_;
shelf handy_depot_shelf_;
};
int main(){
depot name1;
name1.depot_[0].warehouse_[0].rack_[0].shelf_[0].place_[0][0]=1;
return 0; 
}

并且无法弄清楚这是我在理解结构如何工作或如何访问嵌套数组中的特定"单元格"方面的问题。

您的库正在使用超过65545 * 2 * 128 * 128 * 128 * 128 * sizeof(unsigned short)字节的内容作为内存。当然,这对于自动存储的典型实现("堆栈"......通常限制为 1 到 8 MB 之间的内容 AFAIK(。

结构的嵌套是正确的...只是很多。

我建议将设计更改为:

struct Position {
unsigned warehouse;
unsigned rack;
unsigned shelf;
unsigned place;
unsigned row;
unsigned column;
};
struct Depot {
std::unordered_map<Position, unsigned short> places;
}

以上当然不是一个完整的实现,你还需要考虑如何处理像handy_depot_shelf这样的事情,但我希望你明白这个想法。

访问方式

the_depot.places[{0, 0, 0, 0, 0, 0}] = 1;

当然,这只是为了演示目的;你应该在成员函数中隐藏它,并执行边界检查等操作。


如果你不能使用std::unordered_map(赋值?(,那么你需要自己实现一个替代方案。一个非常简单的开始是每个节点中都有键和值的链表。循环访问列表,直到找到具有匹配键的节点,然后返回对值的引用。否则,添加带有键和值的新节点,返回对该值的引用。