结构对象的相等 [英] Equality of structure objects

查看:88
本文介绍了结构对象的相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在matlab中有一个这样的树结构:

I have a tree structure in matlab like this:

node = 
  sub: [1x4 struct]

每个子节点也是一个节点.

where each sub is also a node.

node.sub(1) = 
   sub: [1x4 struct]

等叶节点具有空子.假设我有一个节点,并且正在遍历树.有什么方法可以检查节点对象"是否与树中的节点相同?我不是在说相同的价值.我希望对象"相同.

etc. with leaf nodes having empty sub. Suppose I have a node and I am traversing down the tree. Is there any way to check if the node 'object' is the same as any in the tree? I am not talking about the value being the same. I want the 'object' to be the same.

例如:

mynode = tree.sub(1).sub(1);
isobjectequal(mynode, tree.sub(1).sub(1))

推荐答案

在您所说的意义上,MATLAB中的struct从技术上讲不是对象".如果我创建一个结构,然后将其分配为另一个结构中的字段,则这两个现在将解耦.对第一个结构所做的任何更改都不会反映在我们刚刚制作的副本中.

A struct in MATLAB is not technically an "object" in the sense that you're talking about it. If I create a struct and then assign it as a field within another struct, the two are now uncoupled. Any changes made to the first struct will not be reflected in the copy we just made.

a = struct('a', 2);
b = struct('b', a);

a.a = 3

% b.b.a == 2

您实际上只能可靠地检查两个struct是否相等.

You can really only reliably check that the values of two structs are equal.

如果您实际上想验证要比较的两个struct是否以相同的方式创建,则可以递归地遍历struct并确定每个元素的内存位置是相同的.这意味着该结构既是又是相等,并且它们是使用相同的基础数据创建的.

If you actually want to verify that the two structs that you're comparing were created in the same way, you could go through the struct recursively and determine whether the memory location of each element is the same in both structs. This would imply that the struct is both equal and they were created with the same underlying data.

对于一个非常简单的非深层嵌套结构,它可能看起来像这样.

For a very simple non-deeply nested struct this could look something like this.

function bool = isSameStruct(A, B)

    fmt = get(0, 'Format');

    format debug;
    memoryLocation = @(x)regexp(evalc('disp(x)'), '(?<=pr\s*=\s*)[a-z0-9]*', 'match');

    if isequaln(A, B)
        bool = true;
    elseif ~isequal(sort(fieldnames(A)), sort(fieldnames(B)))
        bool = false;
    else
        fields = fieldnames(A);

        bool = true;

        for k = 1:numel(fields)
            if ~isequal(memoryLocation(A.(fields{k})), memoryLocation(B.(fields{k})))
                bool = false;
                break;
            end
        end
    end

    format(fmt);
end

更新

另一种选择是对节点使用实际的handle对象.一个基本的类看起来像这样.

An alternative is to use actual handle objects for your nodes. A basic class would look like this.

classdef Node < handle
    properties
        Value
        Children
    end

    methods
        function self = Node(value)
            self.Value = value;
        end

        function addChild(self, node)
            self.Children = cat(2, self.Children, node)
        end
    end
end

这篇关于结构对象的相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆