6.1.2结构体数组

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

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-2025 Octave中文网

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