6.1.2 结构体数组

结构体数组是结构体的一种特定实例,其中结构体的每个字段都由一个元胞数组表示。这些元胞数组中的每一个都具有相同的维度。从概念上讲,结构体数组也可以看作是具有相同字段的结构体的数组。创建结构体数组的示例如下:

x(1).a = "string1";
x(2).a = "string2";
x(1).b = 1;
x(2).b = 2;

这将创建一个具有两个字段的 1×2 结构体数组。创建结构体数组的另一种方法是使用 struct 函数(参见 创建结构体)。如前所述,要打印结构体数组的值,可以输入其名称:

x
     ⇒   x =
        {
          1x2 struct array containing the fields:

            a
            b
        }

结构体数组的各个元素可以通过对变量进行索引来返回,例如 x(1),将返回一个包含两个字段的结构体:

x(1)
     ⇒   ans =
        {
          a = string1
          b =  1
        }

此外,如果通过其自身的某个字段名进行索引,结构体数组可以返回字段值的逗号分隔列表(参见 逗号分隔列表)。例如:

x.a
     ⇒ 
        ans = string1
        ans = string2

下面是另一个例子,在赋值语句的左侧使用逗号分隔列表:

[x.a] = deal ("new string1", "new string2");
 x(1).a
     ⇒   ans = new string1
 x(2).a
     ⇒   ans = new string2

与数值数组一样,也可以使用向量作为索引(参见 索引表达式):

x(3:4) = x(1:2);
[x([1,3]).a] = deal ("other string1", "other string2");
x.a
     ⇒ 
        ans = other string1
        ans = new string2
        ans = other string2
        ans = new string2

size 函数将返回结构体的尺寸。对于上面的例子:

size (x)
     ⇒   ans =

          1   4

通过将元素赋值为空矩阵,可以以与数值数组类似的方式从结构体数组中删除元素。例如:

in = struct ("call1", {x, Inf, "last"},
             "call2", {x, Inf, "first"})
     ⇒   in =
        {
          1x3 struct array containing the fields:

            call1
            call2
        }

in(1) = [];
in.call1
     ⇒ 
       ans = Inf
       ans = last

版权所有 © 2024-2026 Octave中文网

ICP备案/许可证号:黑ICP备2024030411号-4