A.1.5 Структуры в Oct-файлах
Структура в Octave — это отображение набора полей в их значения. Используется класс Standard Template Library map, где пара состоит из std::string и переменной Octave Cell.
Простой пример использования структур в oct-файлах:
#include <octave/oct.h>
#include <octave/ov-struct.h>
DEFUN_DLD (structdemo, args, , "Struct Demo")
{
if (args.length () != 2)
print_usage ();
if (! args(0).isstruct ())
error ("structdemo: ARG1 must be a struct");
octave_scalar_map arg0 = args(0).scalar_map_value ();
//octave_map arg0 = args(0).map_value ();
if (! args(1).is_string ())
error ("structdemo: ARG2 must be a character string");
std::string arg1 = args(1).string_value ();
octave_value tmp = arg0.contents (arg1);
//octave_value tmp = arg0.contents (arg1)(0);
if (! tmp.is_defined ())
error ("structdemo: struct does not have a field named '%s'\n",
arg1.c_str ());
octave_scalar_map st;
st.assign ("selected", tmp);
return octave_value (st);
} Пример использования:
x.a = 1; x.b = "test"; x.c = [1, 2]; structdemo (x, "b") ⇒ selected = test
В приведённом выше примере используется класс octave_scalar_map, предназначенный для представления одной структуры. Для массивов структур вместо него используется класс octave_map. Закомментированный код показывает, как можно изменить пример для работы с массивом структур. В этом случае метод contents возвращает Cell, который может содержать более одного элемента. Поэтому для получения базового octave_value в примере с одной структурой мы бы написали:
octave_value tmp = arg0.contents (arg1)(0);
где завершающий (0) — это оператор () для объекта Cell. Если бы это был настоящий массив структур с несколькими элементами, мы могли бы перебирать элементы с помощью оператора ().
Структуры — это относительно сложные контейнеры данных, и в oct-map.h доступно больше функций, упрощающих работу с ними по сравнению с использованием только contents.
© 1996–2026 The Octave Project Developers
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://docs.octave.org/v9.4.0/Structures-in-Oct_002dFiles.html