Bug, feature, or misuse? Issue with map container

5 次查看(过去 30 天)
I'm using Matlab 2012a and I'm trying out map containers and I came across what I think is a bug. I have a variable which is a structure and one of the elements in this structure is a map container. I want to make a copy of the map container and make it a new element in the structure. I then update a value on one of the container values and I find that both containers are updated with the new value.
For example:
X = 10;
Test.Obj1 = containers.Map({'X'},{X});
when I examine the contents, Test.Obj1('X'), I get 10. Now I make a new container and set it equal to the Obj1 container
Obj2 = Test.Obj1;
Now change the value in this new container
Obj2('X') = 20;
Now if I examine Test.Obj1('X') it now equals 20 instead of 10.
Is this a bug or am I misunderstanding containers?
Thanks!
  3 个评论
Jason
Jason 2013-2-27
Ok, the solution I came up with was to create a function that creates a the container and when call that function to create the "copy".
Not sure if there's a better solution out there so would welcome comments.
Thanks!
Honglei Chen
Honglei Chen 2013-2-27
I don't know what's in your function but I have an example below in my answer.

请先登录,再进行评论。

回答(1 个)

Honglei Chen
Honglei Chen 2013-2-27
Here is an example
h1 = containers.Map({'X','Y'},{'X','Y'})
h2 = containers.Map(h1.keys,h1.values)
h2('Z') = 'Z'
h1
HTH
  1 个评论
P Lepage
P Lepage 2020-10-29
It's crazy that there is no official feature to do that, but can manage to find a workaround.
I have data structure made of map<char, map<... etc>>. Since maps stays handles when put in other maps, the solution you provided does not work.
One day I was experimenting with Data Dictionaries (Simulink) and found that the wrapper class Entry returns a deep clone of the object it holds when you call getEntry.
I ended up writing a function that uses this accidental feature to clone my data structure, but it's to slow to be used in a program.
Conclusion : Matlab can break deep references to handle objects, but it wont let you.

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by