【问题标题】:std::map - inserting a body that is a nested structurestd::map - 插入一个嵌套结构体
【发布时间】:2011-04-22 19:29:12
【问题描述】:

以下insert 有效吗?我的问题的原因是身体中有另一个结构,其中还有另一个结构(数组)。所有变量abcxyz 都是次要的,只是为了支持我的问题。

提前致谢。

struct S_A
{
    int a;
    float b;
    char c;
    // ...
    S_B my_double_nested_structure;
};

struct S_B
{
    int x;
    float y;
    char z;
    // .. .
    char array1[2];
};

typedef std::map<int, S_A> myAMapType;

S_A nestedStruct;
nestedStruct.a = 5;
nestedStruct.b = 5.9;
nestedStruct.c = 'A';
nestedStruct.my_double_nested_structure.x = 4;
nestedStruct.my_double_nested_structure.y = 8.9;
nestedStruct.my_double_nested_structure.z = 'B';
nestedStruct.my_double_nested_structure.array1[0] = 'B';
nestedStruct.my_double_nested_structure.array1[1] = 'C';

main()
{
    myAMapType finalMap;
    finalMap.insert(std::pair<int, S_A>(3, nestedStruct);
}

【问题讨论】:

  • 要格式化代码,要么缩进四个空格,要么选择它并点击{}按钮。
  • @seymoure:谢谢,会的

标签: c++ insert nested structure stdmap


【解决方案1】:

如果您在 struct S_A 之前定义 struct S_B,您的代码将编译并工作,因为您将类型 S_B 的成员对象放入 S_A 定义,这意味着必须在该点定义完整类型 S_B(如果它只是指针反对然后不完整的类型就足够了)。

而且你必须分配作业

nestedStruct.a = 5;
nestedStruct.b = 5.9;
nestedStruct.c = 'A';
nestedStruct.my_double_nested_structure.x =4;
nestedStruct.my_double_nested_structure.y =8.9;
nestedStruct.my_double_nested_structure.z ='B';
nestedStruct.my_double_nested_structure.array1[0] ='B';
nestedStruct.my_double_nested_structure.array1[1] ='C';

进入一些功能。在全局范围内只允许声明/定义(而不是表达式语句等)。

在全局范围内,您可以为结构使用初始化列表:

S_A nestedStruct = { 5, 5.9, 'A', { 4, 8.9, 'B', { 'B', 'C' } } };

对于没有显式构造函数的类(如您的结构)以及此类类的数组或简单类型的数组,允许使用初始化列表。

【讨论】:

    【解决方案2】:

    是的。只要没有指针,它就会全部编译为一个可以复制的整体对象(例如,复制到容器中)。

    由于对 S_B 的前向引用、缺少括号等,您的代码也不会编译。

    【讨论】:

      【解决方案3】:

      这种方法有效(除了代码中的拼写错误等)。原因如下:

      映射将复制的对象(在您的情况下为 S_A)构造到其内部数据中。 S_A 也有一个默认(自动生成的)复制构造函数,它一个接一个地复制它的所有字段,并调用 S_B 的复制构造函数来复制字段my_double_nested_structure。它还有一个默认的复制构造函数,它按顺序复制它的所有字段。

      因此,在插入过程中,所有数据都会正确复制到地图中。

      请记住,如果这些结构有任何指针,那么指针本身将被复制——而不是它们指向的对象。

      【讨论】:

        【解决方案4】:

        正如其他人所指出的,代码应该可以工作,除了拼写错误。通常我会使用[]-operator 来插入地图,例如finalMap[3]=nestedStruct.

        【讨论】:

        • 两种语法都有其用途,并且如果该键已经有一个条目,则具有不同的行为。您的版本将覆盖该条目;问题中的版本不会。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-06
        • 2020-10-27
        • 2010-09-10
        • 2015-05-06
        • 2019-08-19
        相关资源
        最近更新 更多