首页 > 解决方案 > 比较具有相同内容的两个不同结构的内容

问题描述

我有两个包含相同内容的结构,但它们并不相同。

struct ContainerType1 {
    uint8_t   isXYZ;
    uint32_t  foo;
    uint8_t   bar;
    uint32_t  nbOfItems;
    typeXX    ArryXXX[20]; };

struct ContainerType2 {
        uint8_t   isZ;
        uint32_t  x;
        uint8_t   y;
        uint8_t   z;
        uint32_t  nbOfItems;
        typeXX    ArryYY[20]; };

我只想比较这些结构中选定元素的对象。

bool CompareItems (ContainerType1  object1, ContainerType2  object2)
{
   if(object1.nbOfItems != object1.nbOfItems or object1.isXYZ != object1.isZ)
   {
       return false; 
   }

   for (int i=0; i< nbOfItems ; i++)
   {
        p1 = object1.ArryXXX;
        p2 = object2.ArryYY;

        if(p1.numberOfFoo != p2.numberOfBar)
           return false;
        if(p1.Foo.x != p2.Bar.x )
           return false;
        if(p1.a.y != p2.b.y )
           return false;
   }

   return true;
}

**我没有能力改变/重新设计这些结构。我只能用它们来比较。

有一个更好的方法吗?就像将我想要比较的所有内容(整数和枚举)按顺序放在两个数组中并进行比较?

标签: c++

解决方案


正如问题下的评论所建议的那样,一种简单的方法是在其中一个结构下使用 == 运算符。

它看起来像这样:

struct ContainerType1 {
    uint8_t   isXYZ;
    uint32_t  foo;
    uint8_t   bar;
    uint32_t  nbOfItems;
    typeXX    ArryXXX[20]; 
    
    bool operator == (const ContainerType2& other) const {
        // everything you want to compare in here
        // for example
        if (isXYZ != other.isZ) return false;
        // ...
    }
};

struct ContainerType2 {
    uint8_t   isZ;
    uint32_t  x;
    uint8_t   y;
    uint8_t   z;
    uint32_t  nbOfItems;
    typeXX    ArryYY[20]; 
};

然后要比较它们,您可以简单地执行以下操作:

ContainerType1 a;
ContainerType2 b;
cout << (a == b) << endl;

推荐阅读