Matlab 的 containers.Map 可以创建一种将值映射到唯一键的数据结构(或者说对象)。它特别适合用于存储键值对和按键查找。
语法
M = containers.Map(keySet,valueSet)用法
keySet 指定键,类型可以是 numeric array、cell array of character vectors 或 string array。
valueSet 指定值,类型是数组(数值数组或元胞数组)。
示例
以下代码片段来自我写的一个程序,该程序从 excel 表格中导入变量的声明和定义,生成 c 代码文件。
TypeIndexPair = {'single', 7;...
'float', 7;...
'double', -7;...
'logical', 1;...
'boolean', 1;...
'int32', -4;...
'int16', -2;...
'int8', -1;...
'uint32', 4;...
'uint16', 2;...
'uint8', 1};
TypeMap = containers.Map(TypeIndexPair(:,1),TypeIndexPair(:,2));
%% Test
index = TypeMap('double');首先,我把数据类型及其索引写入元胞数组 TypeIndexPair。接着,取 TypeIndexPair 数组的第一列和第二列构建 Map 数据结构 TypeMap。最后,通过 TypeMap('type') 得到 type 对应的索引值。
补充信息
containers.map 对象包含以下函数
| 函数 | |
|---|---|
| isKey | 判断 Map 对象是否包含某个键 |
| keys | 返回 Map 对象的键 |
| length | Map 对象中键值对的数量 |
| remove | 从 Map 对象中删除键值对 |
| size | Map 对象的大小 |
| values | 返回 Map 对象的值 |
另外,如果想查看某个对象有哪些方法,可以试试 methods 或 methodsview 函数。下面是 methodsview(TypeMap) 的输出。

0 条评论