Why does containers​.Map('KeyT​ype','doub​le') silently return a map with KeyType 'char' ?

10 vues (au cours des 30 derniers jours)
I would have expected an error if the second argument is strictly required. Giving me a wrong map just pushes the error to runtime when I call it with an 'double' key. No idea what went into this design.

Réponse acceptée

Walter Roberson
Walter Roberson le 1 Fév 2025
containers.Map('KeyType','double')
ans =
Map with properties: Count: 1 KeyType: char ValueType: char
is interpreted as being an instance of calling
M = containers.Map(keySet,valueSet)
You need to provide the 'ValueType' on the same call in order for it to be interpreted as keytype
c = containers.Map('KeyType','double','ValueType','double')
c = Map with properties: Count: 0 KeyType: double ValueType: double
  3 commentaires
Vijay
Vijay le 1 Fév 2025
(I do appreciate the quick response @Walter Roberson)
Steven Lord
Steven Lord le 3 Fév 2025
If we allowed users to specify just the KeyType or just the ValueType, the call you wrote would be ambiguous. Do you intend to set just the type and populate the containers.Map object with no data, or did you intend to create a containers.Map object with just one piece of data, where the key just happened to be either 'KeyType' or 'ValueType'?
With the design as implemented, there's no ambiguity. With two inputs you're specifying a key and value pair, even if the key is either 'KeyType' or 'ValueType'. If you want to set one of the types without specifying data you have to explicitly set both types to make it clear you're setting the types.
Note that if you wanted to create an object with two keys, both 'KeyType' and 'ValueType', you could specify a cell array of keys and values.
c = containers.Map({'KeyType', 'ValueType'}, {1, 2})
c =
Map with properties: Count: 2 KeyType: char ValueType: double
keys(c)
ans = 1x2 cell array
{'KeyType'} {'ValueType'}

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by