How can I iterate over the keys and elements in a containers.Map?

149 次查看(过去 30 天)
D = containers.Map('air',1)
for k = keys(D)
D(k)
end
Error using containers.Map/subsref
Specified key type does not match the type expected for this container.
Why does the above cause an error?

采纳的回答

KSSV
KSSV 2016-10-14
编辑:KSSV 2016-10-14
D = containers.Map({'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});
k = keys(D) ;
val = values(D) ;
for i = 1:length(D)
[k{i} val{i}]
end
  2 个评论
Steven Lord
Steven Lord 2016-10-14
The code in the original question was very close. The reason it didn't work is because the keys in D are char vectors
>> D = containers.Map({'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'})
D =
Map with properties:
Count: 4
KeyType: char
ValueType: char
The keys method returns a cell array, each cell of which contains one of the char vectors, not a char array itself. This allows containers.Map to return a set of char vector keys that are not the same length without needing to pad the shorter ones to the same length as the longest. To index into D, extract the char vectors from the cell array and use those char vectors as the index.
for k = keys(D)
thekey = k{1}; % The curly braces are the key, so to speak
fprintf('The value associated with key %s is %s.\n', ...
thekey, D(thekey));
end

请先登录,再进行评论。

更多回答(2 个)

Qixiang Zou
Qixiang Zou 2017-8-11
D = containers.Map('air',1)
for k = keys(D)
D(k{1}})
end
This should work. Iterator of cell returns element wrapped in a cell. So, add a stupid {1} can save your code.

Clark Steen
Clark Steen 2024-11-8,4:41
Alternatively, using strings:
D = containers.Map('air',1);
for k = string(D.keys)
D(k)
end
ans = 1

类别

Help CenterFile Exchange 中查找有关 NaNs 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by