A.1.5 Структуры в Oct-файлах
Структура в Octave — это отображение между несколькими полями и их значениями. Используется класс Стандартной библиотеки шаблонов 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–2022 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/v7.2.0/Structures-in-Oct_002dFiles.html